PHP str_replace() Function
Replace the characters «world» in the string «Hello world!» with «Peter»:
Definition and Usage
The str_replace() function replaces some characters with some other characters in a string.
This function works by the following rules:
- If the string to be searched is an array, it returns an array
- If the string to be searched is an array, find and replace is performed with every array element
- If both find and replace are arrays, and replace has fewer elements than find, an empty string will be used as replace
- If find is an array and replace is a string, the replace string will be used for every find value
Note: This function is case-sensitive. Use the str_ireplace() function to perform a case-insensitive search.
Note: This function is binary-safe.
Syntax
Parameter Values
Parameter | Description |
---|---|
find | Required. Specifies the value to find |
replace | Required. Specifies the value to replace the value in find |
string | Required. Specifies the string to be searched |
count | Optional. A variable that counts the number of replacements |
Technical Details
Return Value: | Returns a string or an array with the replaced values |
---|---|
PHP Version: | 4+ |
Changelog: | The count parameter was added in PHP 5.0 |
Before PHP 4.3.3, this function experienced trouble when using arrays as both find and replace parameters, which caused empty find indexes to be skipped without advancing the internal pointer on the replace array. Newer versions will not have this problem.
More Examples
Example
Using str_replace() with an array and a count variable:
$arr = array(«blue»,»red»,»green»,»yellow»);
print_r(str_replace(«red»,»pink»,$arr,$i));
echo «Replacements: $i»;
?>?php
Example
Using str_replace() with fewer elements in replace than find:
$find = array(«Hello»,»world»);
$replace = array(«B»);
$arr = array(«Hello»,»world»,»!»);
print_r(str_replace($find,$replace,$arr));
?>?php
str_replace
Эта функция возвращает строку или массив, в котором все вхождения search в subject заменены на replace .
Если не нужны сложные правила поиска/замены (например, регулярные выражения), использование этой функции предпочтительнее preg_replace() .
Список параметров
Если search и replace — массивы, то str_replace() использует каждое значение из соответствующего массива для поиска и замены в subject . Если в массиве replace меньше элементов, чем в search , в качестве строки замены для оставшихся значений будет использована пустая строка. Если search — массив, а replace — строка, то эта строка замены будет использована для каждого элемента массива search . Обратный случай смысла не имеет.
Если search или replace являются массивами, их элементы будут обработаны от первого к последнему.
Искомое значение, также известное как needle (иголка). Для множества искомых значений можно использовать массив.
Значение замены, будет использовано для замены искомых значений search . Для множества значений можно использовать массив.
Строка или массив, в котором производится поиск и замена, также известный как haystack (стог сена).
Если subject является массивом, то поиск с заменой будет осуществляться над каждым элементом subject , а результатом функции также будет являться массив.
Если передан, то будет установлен в количество произведенных замен.
Возвращаемые значения
Эта функция возвращает строку или массив с замененными значениями.
Примеры
Пример #1 Примеры использования str_replace()
// присваивает: Hll Wrld f PHP
$vowels = array( «a» , «e» , «i» , «o» , «u» , «A» , «E» , «I» , «O» , «U» );
$onlyconsonants = str_replace ( $vowels , «» , «Hello World of PHP» );
// присваивает: 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 );
// присваивает: 2
$str = str_replace ( «ll» , «» , «good golly miss molly!» , $count );
echo $count ;
?>
Пример #2 Примеры потенциальных трюков с str_replace()
// Порядок замены
$str = «Строка 1\nСтрока 2\rСтрока 3\r\nСтрока 4\n» ;
$order = array( «\r\n» , «\n» , «\r» );
$replace = ‘
‘ ;
?php
// Обрабатывает сначала \r\n для избежания их повторной замены.
echo $newstr = str_replace ( $order , $replace , $str );
// Выводит F, т.к. A заменяется на B, затем B на C, и так далее.
// В итоге E будет заменено F, так как замена происходит слева направо.
$search = array( ‘A’ , ‘B’ , ‘C’ , ‘D’ , ‘E’ );
$replace = array( ‘B’ , ‘C’ , ‘D’ , ‘E’ , ‘F’ );
$subject = ‘A’ ;
echo str_replace ( $search , $replace , $subject );
// Выводит: яблорехкорех орех (по вышеуказанной причине)
$letters = array( ‘я’ , ‘о’ );
$fruit = array( ‘яблоко’ , ‘орех’ );
$text = ‘я о’ ;
$output = str_replace ( $letters , $fruit , $text );
echo $output ;
?>
Примечания
Замечание: Эта функция безопасна для обработки данных в двоичной форме.
Замечание о порядке замены
Так как str_replace() осуществляет замену слева направо, то при использовании множественных замен она может заменить ранее вставленное значение на другое. Смотрите также примеры на этой странице.
Замечание:
Эта функция чувствительна к регистру. Используйте str_ireplace() для замены, нечувствительной к регистру.
Смотрите также
- str_ireplace() — Регистронезависимый вариант функции str_replace
- substr_replace() — Заменяет часть строки
- preg_replace() — Выполняет поиск и замену по регулярному выражению
- strtr() — Преобразует заданные символы или заменяет подстроки
str_replace
This function returns a string or an array with all occurrences of search in subject replaced with the given replace value.
To replace text based on a pattern rather than a fixed string, use preg_replace() .
Parameters
If search and replace are arrays, then str_replace() takes a value from each array and uses them to search and replace on subject . If replace has fewer values than search , then an empty string is used for the rest of replacement values. If search is an array and replace is a string, then this replacement string is used for every value of search . The converse would not make sense, though.
If search or replace are arrays, their elements are processed first to last.
The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.
The replacement value that replaces found search values. An array may be used to designate multiple replacements.
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.
If passed, this will be set to the number of replacements performed.
Return Values
This function returns a string or an array with the replaced values.
Examples
Example #1 Basic str_replace() examples
// 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 ;
?>
Example #2 Examples of potential str_replace() gotchas
// Order of replacement
$str = «Line 1\nLine 2\rLine 3\r\nLine 4\n» ;
$order = array( «\r\n» , «\n» , «\r» );
$replace = ‘
‘ ;
?php
// 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 ;
?>
Notes
Note: This function is binary-safe.
Replacement order gotcha
Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. See also the examples in this document.
Note:
This function is case-sensitive. Use str_ireplace() for case-insensitive replace.
See Also
- str_ireplace() — Case-insensitive version of str_replace
- substr_replace() — Replace text within a portion of a string
- preg_replace() — Perform a regular expression search and replace
- strtr() — Translate characters or replace substrings