Strings str_replace

(PHP 4, PHP 5, PHP 7, PHP 8)

str_replace — 검색 문자열의 모든 항목을 대체 문자열로 바꿉니다.


설명

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

이 함수는 주어진 replace 값으로 대체된 subject에서 모든 search이 있는 문자열 또는 배열을 리턴합니다.

멋진 교체 규칙(예: 정규식)이 필요하지 않은 경우 preg_replace() 대신 이 함수를 사용해야 합니다.


매개변수

searchreplace가 배열인 경우 str_replace()는 각 배열에서 값을 가져와 subject를 검색하고 바꾸는 데 사용합니다. replacesearch보다 적은 값을 갖는 경우 나머지 대체 값에 대해 빈 문자열이 사용됩니다. search가 배열이고 replace가 문자열이면 이 대체 문자열은 모든 search 값에 사용됩니다. 그러나 그 반대는 의미가 없을 것입니다.

search 또는 replace가 배열인 경우 해당 요소가 처음부터 마지막으로 처리됩니다.

search
검색 중인 값(needle이라고도 함)입니다. 배열은 여러 needle을 지정하는 데 사용할 수 있습니다.
replace
찾은 search 값을 대체하는 대체 값입니다. 배열을 사용하여 여러 대체품을 지정할 수 있습니다.
subject
haystack라고도 하는 검색 및 대체되는 문자열 또는 배열입니다.

subject가 배열이면 subject의 모든 항목에 대해 검색 및 바꾸기가 수행되고 반환 값도 배열입니다.

count
통과하면 수행된 교체 횟수로 설정됩니다.

반환 값

이 함수는 대체된 값이 있는 문자열 또는 배열을 반환합니다.


Examples

예제 #1 기본 str_replace() 예제

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

// 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");

// Provides: You should eat pizza, beer, and ice cream every day
$phrase  = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables", "fiber");
$yummy   = array("pizza", "beer", "ice cream");

$newphrase = str_replace($healthy, $yummy, $phrase);

// Provides: 2
$str = str_replace("ll", "", "good golly miss molly!", $count);
echo $count;
?>
                  
                

예제 #2 잠재적인 str_replace() 문제의 예

                  
<?php
// Order of replacement
$str     = "Line 1\nLine 2\rLine 3\r\nLine 4\n";
$order   = array("\r\n", "\n", "\r");
$replace = '<br />';

// Processes \r\n's first so they aren't converted twice.
$newstr = str_replace($order, $replace, $str);

// Outputs F because A is replaced with B, then B is replaced with C, and so on...
// Finally E is replaced with F, because of left to right replacements.
$search  = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';
echo str_replace($search, $replace, $subject);

// Outputs: apearpearle pear
// For the same reason mentioned above
$letters = array('a', 'p');
$fruit   = array('apple', 'pear');
$text    = 'a p';
$output  = str_replace($letters, $fruit, $text);
echo $output;
?>
                  
                

메모

참고: 이 함수는 binary-safe입니다.

주의
Replacement order gotcha

str_replace()는 왼쪽에서 오른쪽으로 교체하기 때문에 여러 교체를 수행할 때 이전에 삽입된 값을 교체할 수 있습니다. 이 문서의 예도 참조하십시오.

참고: 이 함수는 대소문자를 구분합니다. 대소문자를 구분하지 않는 교체를 위해 str_ireplace()를 사용하십시오.


기타

  • str_ireplace() - 대소문자를 구분하지 않는 str_replace 버전
  • substr_replace() - 문자열의 일부 내에서 텍스트 바꾸기
  • preg_replace() - 정규식 검색 및 바꾸기 수행
  • strtr() - 문자 번역 또는 부분 문자열 바꾸기