PHP str_replace function
The PHP function str_replace will replace all occurrences of a given text or texts ($search) in a string ($subject) or array of strings with a string given as a parameter/s ($replace).
Description / Descripciónstr_replace( array|string $search, array|string $replace, string|array $subject, int &$count = null ): string|arraySintaxis / Sintax
$replaced =str_replace($search, $replace, $subject); $replaced =str_replace($search, $replace, $subject, $count);
Parameters
$search
– the value to be searched for within $subject, $search can be an array to perform multiple searches.
$replace
– the value by which the value $search will be replaced if found. An array can be used for multiple replacements.
$subject
– is the string or array where the values of $search will be searched for and replaced by the values of $replace.
$count
– the number of replacements to be made.
If $search is an array and $replace is also an array, it will use these arrays to replace the values in $subject.
In case that $replace has fewer values than $search, then empty strings “” will be used for the remaining values of $replace.
$search(array),$replace(string)If $search is an array and $replace is a string, the string will be used for all the values in $search.
$subject(array)If $subject is an array, then the replacements between $search and $replace will be made for each element of $subject, and the returned value is an array with the changes.
Returns
Returns a string or an array with specified values replaced.
PHP str_replace examples
In the examples, we will see the most common case where we can use str_replace
, and then we will see the cases where the parameters are arrays:
The most commonly used form of str_replace
is to change all spaces in " "
to ""
, this is used in the inputs for registration.
$sin_espacios= str_replace(' ', '', $input);
Let’s see what happens when $replace
and $search
are arrays.
//blastcoding.com ejemplo de str_replace $search(array) y $replace(array) $mystring ="Aquí me pongo a cantar, al compás de la vigüela que el hombre que lo desvela una pena extraordinaria, como la ave solitaria con el cantar se consuela."; $newstring = str_replace(array("solitaria","pongo"),array("aislada","situo"),$mystring); print_r($newstring);
Aquí me situo a cantar, al compás de la vigüela que el hombre que lo desvela una pena extraordinaria, como la ave aislada con el cantar se consuela.
If all the parameters are arrays, we could have an example like the following:
str_replace con todos los parametros siendo array$buscar = array("a", "b", "c"); $reemplazar = array("x", "y", "z"); $frase = array("La rapidez del abecedario.", "abc abc abc"); $fraseNueva = str_replace($buscar, $reemplazar, $frase); print_r($fraseNueva);
Array ( [0] => Lx rxpidez del xyezedxrio. [1] => xyz xyz xyz )
str_replace
can be used in conjunction with PHP’s trim function for form inputs.