Académique Documents
Professionnel Documents
Culture Documents
php
str_replace
(PHP 4, PHP 5)
str_replace — Replace all occurrences of the search string with the replacement string
mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )
This function returns a string or an array with all occurrences of search in subject replaced with
the given replace value.
If you don't need fancy replacing rules (like regular expressions), you should always use this
function instead of ereg_replace() or preg_replace().
1 of 17 11/15/2010 5:23 PM
PHP: str_replace - Manual http://php.net/manual/en/function.str-replace.php
If search and replace are arrays, then str_replace() takes a value from each array and uses
them to do 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.
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
Note: If passed, this will hold the number of matched and replaced needles.
Version Description
The behaviour of this function changed. In older versions a bug existed when using
arrays as both search and replace parameters which caused empty search indexes to
4.3.3 be skipped without advancing the internal pointer on the replace array. This has
been corrected in PHP 4.3.3, any scripts which relied on this bug should remove
2 of 17 11/15/2010 5:23 PM
PHP: str_replace - Manual http://php.net/manual/en/function.str-replace.php
Version Description
empty search values prior to calling this function in order to mimic the original
behavior.
<?php
// Provides: <body text='black'>
$bodytag = str_replace("%body%", "black", "<body text='%body%'>");
// 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");
// Provides: 2
$str = str_replace("ll", "", "good golly miss molly!", $count);
echo $count;
?>
3 of 17 11/15/2010 5:23 PM
PHP: str_replace - Manual http://php.net/manual/en/function.str-replace.php
<?php
// Order of replacement
$str = "Line 1\nLine 2\rLine 3\r\nLine 4\n";
$order = array("\r\n", "\n", "\r");
$replace = '<br />';
Caution
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:
4 of 17 11/15/2010 5:23 PM
PHP: str_replace - Manual http://php.net/manual/en/function.str-replace.php
A faster way to replace the strings in multidimensional array is to json_encode() it, do the
str_replace() and then json_decode() it, like this:
<?php
function str_replace_json($search, $replace, $subject){
return json_decode(str_replace($search, $replace, json_encode($subject)));
}
?>
This method is almost 3x faster (in 10000 runs.) than using recursive calling and looping
method, and 10x simpler in coding.
Compared to:
<?php
function str_replace_deep($search, $replace, $subject)
{
if (is_array($subject))
{
foreach($subject as &$oneSubject)
$oneSubject = str_replace_deep($search, $replace, $oneSubject);
unset($oneSubject);
return $subject;
} else {
return str_replace($search, $replace, $subject);
}
}
?>
jpoirier at hotmail.fr
25-Jun-2010 12:40
As of 5.0.0 the last parameter (count) is passed by reference (it is optional). So 2 choices :
1)passed not by reference - it's limit
2)passed by reference : the var is is_null() - all occurences are replaced the number is
returned in "count", otoh if the var !is_null() -> use as limit.
On version 5.3.0 the 4th parameter, count, does not work when not passed
by reference.
http://bugs.php.net/bug.php?id=11457
5 of 17 11/15/2010 5:23 PM
PHP: str_replace - Manual http://php.net/manual/en/function.str-replace.php
If we have a html template that contains placeholders in curly braces that need to be replaced
in runtime, the following function will do it using str_replace:
<?php
?>
cableray
11-Jun-2010 07:03
If you wish to get around the 'gotcha', you could do something like this:
<?php
?>
The idea here is that you first replace the items you want with unique identifiers (that you
are unlikely to find in the subject) and then search for those identifiers and then replace
them.
If you need to replace a string in another, but only once but still in all possible
combinations (f.e. to replace "a" with "x" in "aba" to get array("xba", "abx")) you can use
this function:
<?php
function getSingleReplaceCombinations($replace, $with, $inHaystack)
{
$splits = explode($replace, $inHaystack);
$result = array();
for ($i = 1, $ix = count($splits); $i < $ix; ++$i) {
$previous = array_slice($splits, 0, $i);
$next = array_slice($splits, $i);
6 of 17 11/15/2010 5:23 PM
PHP: str_replace - Manual http://php.net/manual/en/function.str-replace.php
Might be worth mentioning that a SIMPLE way to accomplish Example 2 (potential gotchas) is to
simply start your "replacements" in reverse.
<?php
$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
// replaces A to B, B to C, C to D, D to E, E to F (makes them all F)
// start from "E" and end with "A":
So basically start from the "end" and put the replacements in an order where the "replaced
value" won't equal a value that exists later in the "search array".
Here's a deep replace function allowing multi-dimensional arrays in $search, $replace and
$subject. The keys and other structure of $subject are preserved.
<?php
// Auxiliary function:
function _replaceWithAnything($search,$replace,$subject){
if(!is_array($search) || !is_array($replace)){
$search=array($search);
$replace=array($replace);
}
$match=array_search($subject,$search,true);
if($match!==false && array_key_exists($match,$replace))
$subject=$replace[$match];
return $subject;
}
// Main function:
function deepReplace($search,$replace,$subject){
if(!is_array($subject))
return _replaceWithAnything($search,$replace,$subject);
foreach($subject as &$val){
if(is_array($val)){
$val=deepReplace($search,$replace,$val);
continue;
}
$val=_replaceWithAnything($search,$replace,$val);
}
return $subject;
}
?>
Fast function to replace new lines from a given string. This is interesting to replace all new
lines from e. g. a text formatted in HTML retrieved from database and printing it without the
unnecessary new lines. This results in slightly faster rendering in the Web browser.
7 of 17 11/15/2010 5:23 PM
PHP: str_replace - Manual http://php.net/manual/en/function.str-replace.php
<?php
/**
* Replace all linebreaks with one whitespace.
*
* @access public
* @param string $string
* The text to be processed.
* @return string
* The given text without any linebreaks.
*/
function replace_newline($string) {
return (string)str_replace(array("\r", "\r\n", "\n"), '', $string);
}
?>
Wes Foster
17-Dec-2009 09:32
Feel free to optimize this using the while/for or anything else, but this is a bit of code
that allows you to replace strings found in an associative array.
For example:
<?php
$replace = array(
'dog' => 'cat',
'apple' => 'orange'
'chevy' => 'ford'
);
echo str_replace_assoc($replace,$string);
<?php
function strReplaceAssoc(array $replace, $subject) {
return str_replace(array_keys($replace), array_values($replace), $subject);
}
?>
[Jun 1st, 2010 - EDIT BY thiago AT php DOT net: Function has been replaced with an updated
version sent by ljelinek AT gmail DOT com]
If you get a blank page when passing an object to str_replace() (relying on __toString() to
convert the object to a string) then you may need to force string context using (string), like
so:
<?php
private function _load_vars($vars, &$source = false) {
if(!$source) $source =& $this->code;
foreach((array)$vars as $key => $var) {
8 of 17 11/15/2010 5:23 PM
PHP: str_replace - Manual http://php.net/manual/en/function.str-replace.php
I was running Ubuntu Server with PHP 5.2.6 and getting apache segfaults and mysterious blank
pages when $var happened to be certain objects.
Chris
01-Nov-2009 04:22
Decko
15-Oct-2009 08:41
As mentioned earlier you should take the order into account when substituting multiple values.
However it is worth noticing that str_replace doesn't seem to re-read the string when doing
single replacements. Take the following example.
<?php
$s = '/a/a/';
$s = str_replace('/a/', '/', $s);
?>
<?php
$s = '/a/a/';
while(strpos($s, '/a/') !== false)
$s = str_replace('/a/', '/', $s); //eventually $s will == '/'
?>
Alberto Lepe
16-Jun-2009 02:44
Be careful when replacing characters (or repeated patterns in the FROM and TO arrays):
For example:
<?php
$arrFrom = array("1","2","3","B");
$arrTo = array("A","B","C","D");
$word = "ZBB2";
echo str_replace($arrFrom, $arrTo, $word);
?>
9 of 17 11/15/2010 5:23 PM
PHP: str_replace - Manual http://php.net/manual/en/function.str-replace.php
<?php
$arr = array("1" => "A","2" => "B","3" => "C","B" => "D");
$word = "ZBB2";
echo strtr($word,$arr);
?>
<?php
/*
This is a function for made recursive str_replaces in an array
*/
function recursive_array_replace($find, $replace, &$data) {
if (is_array($data)) {
foreach ($data as $key => $value) {
if (is_array($value)) {
recursive_array_replace($find, $replace, $data[$key]);
} else {
$data[$key] = str_replace($find, $replace, $value);
}
}
} else {
$data = str_replace($find, $replace, $data);
}
}
$a = array();
$a['a'] = "a";
$a['b']['a'] = "ba";
$a['b']['b'] = "bb";
$a['c'] = "c";
$a['d']['a'] = "da";
$a['d']['b'] = "db";
$a['d']['c'] = "dc";
$a['d']['d'] = "dd";
As previous commentators mentioned, when $search contains values that occur earlier in
$replace, str_replace will factor those previous replacements into the process rather than
operating solely on the original string. This may produce unexpected output.
10 of 17 11/15/2010 5:23 PM
PHP: str_replace - Manual http://php.net/manual/en/function.str-replace.php
Example:
<?php
$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'ABCDE';
In the above code, the $search and $replace should replace each occurrence in the $subject
with the next letter in the alphabet. The expected output for this sample is 'BCDEF';
however, the actual output is 'FFFFF'.
<?php
$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';
Since 'A' is the only letter in the $search array that appears in $subject, one would expect
the result to be 'B'; however, replacement number $n does *not* operate on $subject, it
operates on $subject after the previous $n-1 replacements have been completed.
The following function utilizes array_combine and strtr to produce the expected output, and I
believe it is the most efficient way to perform the desired string replacement without prior
replacements affecting the final result.
<?php
/**
* When using str_replace(...), values that did not exist in the original string (but were put
there by previous
* replacements) will be replaced continuously. This string replacement function is designed
replace the values
* in $search with those in $replace while not factoring in prior replacements. Note that this
function will
* always look for the longest possible match first and then work its way down to individual
characters.
*
* The "o" in "stro_replace" represents "original", indicating that the function operates only
on the original string.
*
* @param array $search list of strings or characters that need to be replaced
* @param array $replace list of strings or characters that will replace the corresponding
values in $search
* @param string $subject the string on which this operation is being performed
*
* @return string $subject with all substrings in the $search array replaced by the values in
the $replace array
*/
function stro_replace($search, $replace, $subject)
{
return strtr( $subject, array_combine($search, $replace) );
}
11 of 17 11/15/2010 5:23 PM
PHP: str_replace - Manual http://php.net/manual/en/function.str-replace.php
<?php
$search = array(' ', '&');
$replace = array(' ', '&');
$subject = 'Hello & goodbye!';
// We want to replace the spaces with and the ampersand with &
echo str_replace($search, $replace, $subject); // output:
"Hello&nbsp&&nbspgoodbye!" - wrong!
/*
Note: Run the above code in the CLI or view source on your web browser - the replacement
strings for stro_replace are HTML entities which the browser interprets.
*/
?>
<?php
$search = array('ERICA', 'AMERICA');
$replace = array('JON', 'PHP');
$subject = 'MIKE AND ERICA LIKE AMERICA';
// We want to replace the name "ERICA" with "JON" and the word "AMERICA" with "PHP"
echo str_replace($search, $replace, $subject); // output: "MIKE AND JON LIKE AMJON", which is
not correct
echo stro_replace($search, $replace, $subject); // output: "MIKE AND JON LIKE PHP", which is
correct
?>
Replacement for str_replace in which a multiarray of numerically keyed data can be properly
evaluated with the given template without having a search for 11 be mistaken for two 1's next
to each other
<?php
12 of 17 11/15/2010 5:23 PM
PHP: str_replace - Manual http://php.net/manual/en/function.str-replace.php
$i++;
$s = 2;
}
$strings[$i] .= $char; // store string
}
}
if ($i && $input && is_array($input)) { // input data
foreach ($input as $sub) { // each subarray
if (is_array($sub)) {
$out = ''; // reset output
for ($j = 0; $j <= $i; $j++) { // each number/string member
if ($number = $digits[$j]) { // number
$out .= $sub[$number]; // add value from subarray to output
} else { // string
$out .= $strings[$j]; // add to output
}
}
$a[] = $out;
}
}
return $a;
} // input
} // split
} // template
}
/*
Array
(
[0] => banana: a yellow, healthy fruit
[1] => spinach: a green, healthy vegetable
[2] => salmon: a pink, healthy fish
)
*/
?>
Not sure if this will help anyone but I wrote it for my application and thought I would share
just in case
I tried max at efoxdesigns dot com solution for str_replace_once but it didn't work quite
right so I came up with this solution (all params must be strings):
<?php
function str_replace_once($search, $replace, $subject) {
$firstChar = strpos($subject, $search);
if($firstChar !== false) {
$beforeStr = substr($subject,0,$firstChar);
$afterStr = substr($subject, $firstChar + strlen($search));
return $beforeStr.$replace.$afterStr;
} else {
13 of 17 11/15/2010 5:23 PM
PHP: str_replace - Manual http://php.net/manual/en/function.str-replace.php
return $subject;
}
}
?>
For PHP 4 < 4.4.5 and PHP 5 < 5.2.1 you may occur (like me) in this bug:
http://www.php-security.org/MOPB/MOPB-39-2007.html
<?php
function str_replace_deep( $search, $replace, $subject)
{
$subject = str_replace( $search, $replace, $subject);
return $subject;
}
?>
With PHP 4.3.1, at least, str_replace works fine when working with single arrays but mess it
all with two or more dimension arrays.
<?php
$subject = array("You should eat this","this","and this every day.");
$search = "this";
$replace = "that";
$new = str_replace($search, $replace, $subject);
print_r($new); // Array ( [0] => You should eat that [1] => that [2] => and that every day. )
print_r($new); // Array ( [0] => Array [1] => Array [2] => Array )
?>
14 of 17 11/15/2010 5:23 PM
PHP: str_replace - Manual http://php.net/manual/en/function.str-replace.php
<?php
function replace_accents($str) {
$str = htmlentities($str, ENT_COMPAT, "UTF-8");
$str = preg_replace(
'/&([a-zA-Z])(uml|acute|grave|circ|tilde);/',
'$1',$str);
return html_entity_decode($str);
}
?>
kole
26-Feb-2007 01:48
$badchr = array(
"\xc2", // prefix 1
"\x80", // prefix 2
"\x98", // single quote opening
"\x99", // single quote closing
"\x8c", // double quote opening
"\x9d" // double quote closing
);
<?php
return $subject;
}
?>
15 of 17 11/15/2010 5:23 PM
PHP: str_replace - Manual http://php.net/manual/en/function.str-replace.php
This will return false if there are a different number of $replacements versus number of
occurrences of $search in $subject. Additionally, $search much be exactly one character (if a
string is provided, only the first character in the string will be used). Examples:
<?php
echo str_replace_many('?',array('Jane','banana'),'? is eating a ?.');
?>
15-Jan-2007 09:42
Before spending hours searching your application why it makes UTF-8 encoding into some
malformed something with str_replace, make sure you save your PHP file in UTF-8 (NO BOM).
matt wheaton
30-Mar-2006 03:40
As an effort to remove those Word copy and paste smart quotes, I've found that this works with
UTF8 encoded strings (where $text in the following example is UTF8). Also the elipsis and em
and en dashes are replaced.
There is an "invisible" character after the †for the right side double smart quote that
doesn't seem to display here. It is chr(157).
<?php
$find[] = '“'; // left side double smart quote
$find[] = '†; // right side double smart quote
$find[] = '‘'; // left side single smart quote
$find[] = '’'; // right side single smart quote
$find[] = '…'; // elipsis
$find[] = '—'; // em dash
$find[] = '–'; // en dash
$replace[] = '"';
$replace[] = '"';
$replace[] = "'";
$replace[] = "'";
$replace[] = "...";
$replace[] = "-";
$replace[] = "-";
<?php
$match=array("ONE","TWO","THREE");
$replace=array("TWO WORDS","MANY LETTERS","OTHER IDEAS");
$sample="ONE SAMPLE";
echo str_replace($match,$replace,$sample);
?>
16 of 17 11/15/2010 5:23 PM
PHP: str_replace - Manual http://php.net/manual/en/function.str-replace.php
That is, after replacing "ONE" with "TWO WORDS", process follows with next array item and it
changes "TWO" with "MANY LETTERS".
17 of 17 11/15/2010 5:23 PM