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() — Преобразует заданные символы или заменяет подстроки
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
PHP str_replace() Function
In this article, we will see how to replace the occurrence of the search string with the replacing string using the str_replace() function in PHP, along with understanding their implementation through the examples.
The str_replace() is a built-in function in PHP and is used to replace all the occurrences of the search string or array of search strings by replacement string or array of replacement strings in the given string or array respectively.
str_replace ( $searchVal, $replaceVal, $subjectVal, $count )
Parameters: This function accepts 4 parameters out of which 3 are mandatory and 1 is optional. All of these parameters are described below:
- $searchVal: This parameter can be of both string and array types. This parameter specifies the string to be searched and replaced.
- $replaceVal: This parameter can be of both string and array types. This parameter specifies the string with which we want to replace the $searchVal string.
- $subjectVal: This parameter can be of both string and array types. This parameter specifies the string or array of strings which we want to search for $searchVal and replace with $replaceVal.
- $count: This parameter is optional and if passed, its value will be set to the total number of replacement operations performed on the string $subjectVal.
Return Value: This function returns a string or an array based on the $subjectVal parameter with replaced values.
Approach: If the $searchVal and the $replaceVal arguments are arrays, then all the elements of the $searchVal argument are searched in the $subjectVal string and replaced by the corresponding elements in the $replaceVal argument. If a number of elements in $replaceVal are less than that in $searchVal array, then if there are any occurrences of the additional elements of $searchVal argument in the $subjectVal argument then they will be replaced by an empty string. If the $subjectVal parameter is also an array instead of a string then all of the elements of $subjectVal will be searched.
Consider the below example:
Input: $subjectVal = "It was nice meeting you. May you shine brightly." str_replace('you', 'him', $subjectVal) Output: It was nice meeting him. May him shine brightly. Explanation: Every occurrence of you is replaced with him. Input: $subjectVal = "You eat fruits, vegetables, fiber every day." $searchVal = array("fruits", "vegetables", "fiber") $replaceVal = array("pizza", "beer", "ice cream") str_replace($array1, $array2, $str) Output: You eat pizza, beer, ice cream every day. Explanation: Since both the arguments are arrays, therefore, every element from the first argument is replaced with the corresponding element from the second argument.
Example 1: The below example illustrate the str_replace() function in PHP.