본문 바로가기
PHP

[PHP] 특정 문자열을 변경하는 함수 str_replace()

by 와오우 2026. 2. 26.
반응형

Description

str_replace(
    array|string $search,
    array|string $replace,
    string|array $subject,
    int &$count = null
): string|array

 

 

Parameters 

search
The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.

replace
The replacement value that replaces found search values. An array may be used to designate multiple replacements.

subject
The string or array being searched and replaced on, otherwise known as the haystack.
If subject is an array, then the search and replace is performed with every entry of subject, and the return value is an array as well.

count
If passed, this will be set to the number of replacements performed.

 

일반적으로

str_replace(찾는부분, 바꿀부분, 전체문자열) 방식으로 사용한다.

또 string이 아닌 배열이 파라미터로 들어올 수 있다.

 

Examples

<?php
// Provides: <body text='black'>
$bodytag = str_replace("%body%", "black", "<body text='%body%'>");
echo $bodytag, PHP_EOL;

// Provides: Hll Wrld f PHP
$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
echo $onlyconsonants, PHP_EOL;

?>

 

※ PHP코드에서 자주보이는 구문이며,

일반적인 문자열 변경이나 보안을 위해 태그 입력 방지 등의 구문에서도 사용하고 있다.

<?php
$str=str_replace("<","&lt;",$str)
$str=str_replace(">","&gt;",$str);
?>

 

 

* htmlspecialchars() 또는 strip_tags() 을 통해 사용하는 것이 일반적이지만

경우에 따라 태그 열고 닫는 문자만 변경고자 할 경우에는 위와 같은 방식을 사용하기도 한다.

반응형

댓글