Vous êtes sur la page 1sur 17

PHP: str_replace - Manual http://php.net/manual/en/function.str-replace.


Last updated: Fri, 12 Nov 2010

(PHP 4, PHP 5)

str_replace — Replace all occurrences of the search string with the replacement string

Description Report a bug

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

Parameters Report a bug

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.


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

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.


Note: If passed, this will hold the number of matched and replaced needles.

Return Values Report a bug

This function returns a string or an array with the replaced values.

Changelog Report a bug

Version Description

5.0.0 The count parameter was added.

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

4.0.5 Most parameters can now be an array.

Examples Report a bug

Example #1 Basic str_replace() examples

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

3 of 17 11/15/2010 5:23 PM
PHP: str_replace - Manual http://php.net/manual/en/function.str-replace.php

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 = '<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;

Notes Report a bug

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


This function is case-sensitive. Use str_ireplace() for case-insensitive replace.

See Also Report a bug

str_ireplace() - Case-insensitive version of str_replace.

substr_replace() - Replace text within a portion of a string

4 of 17 11/15/2010 5:23 PM
PHP: str_replace - Manual http://php.net/manual/en/function.str-replace.php

preg_replace() - Perform a regular expression search and replace

strtr() - Translate characters or replace substrings

User Contributed Notes

nikolaz dot tang at hotmail dot com
12-Nov-2010 04:57

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:

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:

function str_replace_deep($search, $replace, $subject)
if (is_array($subject))
foreach($subject as &$oneSubject)
$oneSubject = str_replace_deep($search, $replace, $oneSubject);
return $subject;
} else {
return str_replace($search, $replace, $subject);

jpoirier at hotmail.fr
25-Jun-2010 12:40

I've found something interesting about the $count param:

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.


Hope this help

apmuthu at usa dot net

19-Jun-2010 07:31

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:


function parse_template($filename, $data) {

// example template variables {a} and {bc}
// example $data array
// $data = Array("a" => 'one', "bc" => 'two');
$q = file_get_contents($filename);
foreach ($data as $key => $value) {
$q = str_replace('{'.$key.'}', $value, $q);
return $q;


11-Jun-2010 07:03

If you wish to get around the 'gotcha', you could do something like this:


$find=array('a', 'p', '^', '*');

$replace = array('^', '*', 'apple', 'pear');
str_replace($find, $replace, 'a p');


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

christian dot reinecke at web dot de

14-May-2010 07:06

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:
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);

$combine = array_pop($previous) . $with . array_shift($next);

$result[] = implode($replace, array_merge($previous, array($combine), $next));
return $result;
var_dump(getSingleReplaceCombinations("a", "x", "aba")); // result as mentioned above
It may not be the best in performance, but it works.

jbarnett at jmbelite dot com

26-Apr-2010 08:23

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.

So instead of starting from "A" and ending with "E":

$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":

$search = array('E', 'D', 'C', 'B', 'A');

$replace = array('F', 'E', 'D', 'C', 'B');
// replaces E to F, D to E, C to D, B to C, A to B (prevents from
// multiple replacements of already replaced values)

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".

pjcdawkins at googlemail dot com

24-Apr-2010 12:23

Here's a deep replace function allowing multi-dimensional arrays in $search, $replace and
$subject. The keys and other structure of $subject are preserved.

// Auxiliary function:
function _replaceWithAnything($search,$replace,$subject){
if(!is_array($search) || !is_array($replace)){
if($match!==false && array_key_exists($match,$replace))
return $subject;

// Main function:
function deepReplace($search,$replace,$subject){
return _replaceWithAnything($search,$replace,$subject);
foreach($subject as &$val){
return $subject;

fleshgrinder at gmx dot at

16-Apr-2010 12:50

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


* 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:
$replace = array(
'dog' => 'cat',
'apple' => 'orange'
'chevy' => 'ford'

$string = 'I like to eat an apple with my dog in my chevy';

echo str_replace_assoc($replace,$string);

// Echo: I like to eat an orange with my cat in my ford


Here is the function:

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]

jonathon at compwright dot com

12-Nov-2009 05:23

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

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

$source = str_replace("{".$key."}", (string) $var, $source);


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.

01-Nov-2009 04:22

Compress a string's internal spaces:

$str = ' This is a test ';
$count = 1;
$str = str_replace(' ', ' ', $str, $count);

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.

$s = '/a/a/';
$s = str_replace('/a/', '/', $s);

You would expect the following.

First replacement '/a/a/' -> '/a/'

Second replacement '/a/'->'/'

This is not the case, the actual result will be '/a/'.

To fix this, you will have to put str_replace in a while-loop.

$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:

$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

I would expect as result: "ZDDB"

However, this return: "ZDDD"
(Because B = D according to our array)

To make this work, use "strtr" instead:

$arr = array("1" => "A","2" => "B","3" => "C","B" => "D");
$word = "ZBB2";
echo strtr($word,$arr);

This returns: "ZDDB"

moz667 at gmail dot com

21-May-2009 04:49

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

echo "Before Replaces";


recursive_array_replace("a", "XXXX", $a);

echo "After Replaces";


michael dot moussa at gmail dot com

29-Jan-2009 02:38

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


$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'ABCDE';

echo str_replace($search, $replace, $subject); // output: 'FFFFFF'


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'.

To more clearly illustrate this, consider the following example:

$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';

echo str_replace($search, $replace, $subject); // output: 'F'


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.

* 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
* 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

$search = array('A', 'B', 'C', 'D', 'E');

$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'ABCDE';

echo stro_replace($search, $replace, $subject); // output: 'BCDEF'


Some other examples:

$search = array(' ', '&');
$replace = array('&nbsp;', '&amp;');
$subject = 'Hello & goodbye!';

// We want to replace the spaces with &nbsp; and the ampersand with &amp;
echo str_replace($search, $replace, $subject); // output:
"Hello&amp;nbsp&amp;&amp;nbspgoodbye!" - wrong!

echo stro_replace($search, $replace, $subject); // output: "Hello&nbsp;&amp;&nbsp;goodbye!" -


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.

$search = array('ERICA', 'AMERICA');
$replace = array('JON', 'PHP');

// 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

nospam at nospam dot com

02-Dec-2008 10:55

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


function data_template($input, $template) {

if ($template) { // template string
if ($split = str_split($template)) { // each char as array member
foreach ($split as $char) { // each character
if (is_numeric($char)) { // test for digit
if ($s != 1) { // new digit sequence
$s = 1;
$digits[$i] .= $char; // store digit
} else { // not a digit
if ($s != 2) { // new non-digit sequence

12 of 17 11/15/2010 5:23 PM
PHP: str_replace - Manual http://php.net/manual/en/function.str-replace.php

$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

$input = array(array(1=>'yellow', 2=>'banana', 11=>'fruit'), array(1=>'green', 2=>'spinach',

11=>'vegetable'), array(1=>'pink', 2=>'salmon', 11=>'fish'));

print_r (data_template($input, '2: a 1, healthy 11'));

[0] => banana: a yellow, healthy fruit
[1] => spinach: a green, healthy vegetable
[2] => salmon: a pink, healthy fish

// str_replace would have wanted to output 'banana: a yellow, healthy yellowyellow


Not sure if this will help anyone but I wrote it for my application and thought I would share
just in case

nick at NOSPAM dot pitchinteractive dot com

06-Oct-2008 11:12

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):

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;

paolo A T doppioclick D O T com

05-Sep-2008 11:15

For PHP 4 < 4.4.5 and PHP 5 < 5.2.1 you may occur (like me) in this bug:


troy at troyonline dot com

23-Jun-2008 05:18

Yet another deep replace function:

function str_replace_deep( $search, $replace, $subject)
$subject = str_replace( $search, $replace, $subject);

foreach ($subject as &$value)

is_array( $value) and $value =str_replace_deep( $search, $replace, $value);

return $subject;

David Gimeno i Ayuso (info at sima dot cat)

09-Aug-2007 07:22

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.

$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. )

echo "<hr />";

$subject = array(array("first", "You should eat this")

,array("third", "and this every day."));
$search = "this";
$replace = "that";
$new = str_replace($search, $replace, $subject);

print_r($new); // Array ( [0] => Array [1] => Array [2] => Array )


tim at hysniu dot com

05-Jun-2007 06:27

I found that having UTF-8 strings in as argument didnt

work for me using heavyraptors function.
Adding UTF-8 as argument on htmlentities

14 of 17 11/15/2010 5:23 PM
PHP: str_replace - Manual http://php.net/manual/en/function.str-replace.php

fixed the problem.

cheers, tim at hysniu.com

function replace_accents($str) {
$str = htmlentities($str, ENT_COMPAT, "UTF-8");
$str = preg_replace(
return html_entity_decode($str);


26-Feb-2007 01:48

My input is MS Excel file but I want to save ‘,’,“,” as ',',",".

$badchr = array(
"\xc2", // prefix 1
"\x80", // prefix 2
"\x98", // single quote opening
"\x99", // single quote closing
"\x8c", // double quote opening
"\x9d" // double quote closing

$goodchr = array('', '', '\'', '\'', '"', '"');

str_replace($badchr, $goodchr, $strFromExcelFile);

Works for me.

rlee0001 at sbcglobal dot net

16-Feb-2007 08:30

This is a more rigid alternative to spectrereturns at creaturestoke dot com's

replace_different function:


function str_replace_many ($search, $replacements, $subject) {

$index = strlen($subject);
$replacements = array_reverse($replacements);

if (count($replacements) != substr_count($subject, $search)) {

return FALSE;

foreach ($replacements as $replacement) {

$index = strrpos(substr($subject, 0, $index), $search);
$prefix = substr($subject, 0, $index);
$suffix = substr($subject, $index + 1);
$subject = $prefix . $replacement . $suffix;

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:

echo str_replace_many('?',array('Jane','banana'),'? is eating a ?.');

prints: "Jane is eating a banana."

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).

This was at least one of my problems.

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).

$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[] = "-";

$text = str_replace($find, $replace, $text);


David Gimeno i Ayuso (info at sima-pc dot com)

25-Aug-2003 01:12

Take care with order when using arrays in replacement.

$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".

Copyright © 2001-2010 The PHP Group

All rights reserved.

17 of 17 11/15/2010 5:23 PM