downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

str_rot13> <str_repeat
Last updated: Fri, 13 Nov 2009

view this page in

str_replace

(PHP 4, PHP 5)

str_replaceSubstitui todas as ocorrências da string de procura com a string de substituição

Descrição

mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

Esta função retorna uma string ou um array com todas as ocorrências de search em subject substituídas com o valor dado para replace .

Se você não precisa de regras de substituição especiais (como expressões regulares), você sempre poderia usar esta função ao invés de ereg_replace() ou preg_replace().

Parâmetros

Se search e replace são arrays, então str_replace() pega o valor de cada array e os usa para fazer a pesquisa e a substituição em subject . Se replace tem menos valores do que search , então uma string vazia é usada para o restante dos valores de substituição. Se search é um array e replace é uma string, então esta string de substituição é usada para cada valor de search . O contrário não faria sentido, contudo.

Se search ou replace são arrays, seus elementos são processados do primeiro ao último.

search

replace

subject

Se subject é um array, então a pesquisa e a substituição é executada com cada entrada de subject , e o valor de retorno é um array também.

count

Nota: Se passado, guardará o número de combinações e modificações feitas.

Valor Retornado

Esta função retorna uma string ou um array com os valores modificados.

Histórico

Versão Descrição
5.0.0 O parâmetro count foi adicionado.
4.3.3 O comportamento desta função foi modificado. Em antigas versões um bug existia ao se usar arrays em ambos os parâmetros search e replace que causava índices de search vazios para serem pulados sem avançar o apontador interno no array replace . Isto foi corrigido no PHP 4.3.3, quaisquer scripts que contavam com este bug removeriam valores de pesquisa vazios anteriores à chamada desta função afim de imitar o comportamento original.
4.0.5 Mais parâmetros podem agora ser um array.

Exemplos

Exemplo #1 Exemplos da str_replace()

<?php
// Fornece: <body text='black'>
$bodytag str_replace("%body%""black""<body text='%body%'>");

// Fornece: Hll Wrld f PHP
$vowels = array("a""e""i""o""u""A""E""I""O""U");
$onlyconsonants str_replace($vowels"""Hello World of PHP");

// Fornece: você comeria pizza, cerveja e sorvete todos os dias
$frase  "você comeria frutas, vegetais, e fibra todos os dias.";
$saudavel = array("frutas""vegetais""fibra");
$saboroso   = array("pizza""cerveja""sorvete");

$novafrase str_replace($saudavel$saboroso$frase);

// Uso do parâmetro count está disponível no PHP 5.0.0
$str str_replace("ll""""good golly miss molly!"$count);
echo 
$count// 2

// 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: apearpearle pear
$letters = array('a''p');
$fruit   = array('apple''pear');
$text    'a p';
$output  str_replace($letters$fruit$text);
echo 
$output;
?>

Notas

Nota: Esta função é compatível com dados binários

Nota: Esta função é case-sensitive. Use str_ireplace() para substituição case-insensitive.

Veja Também

  • str_ireplace() - Versão que não diferencia maiúsculas e minúsculas de str_replace.
  • substr_replace() - Substitui o texto dentro de uma parte de uma string
  • preg_replace() - Perform a regular expression search and replace
  • strtr() - Traduz certos caracteres



str_rot13> <str_repeat
Last updated: Fri, 13 Nov 2009
 
add a note add a note User Contributed Notes
str_replace
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 so:

<?php
private function _load_vars($vars, &$source = false) {
    if(!
$source) $source =& $this->code;
        foreach((array)
$vars as $key => $var) {
           
$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.
Chris
01-Nov-2009 04:22
Compress a string's internal spaces:
<?php
$str
= ' This is    a    test   ';
$count = 1;
while(
$count)
   
$str = str_replace('  ', ' ', $str, $count);
?>
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);
?>

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.

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

I would expect as result: "ZDDB"
However, this return: "ZDDD"
(Because B = D according to our array)

To make this work, use "strtr" instead:

<?php
$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
<?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";

echo
"Before Replaces";
print_r($a);

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

echo
"After Replaces";
print_r($a);
?>
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.

Example:

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

<?php
$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.

<?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) );
}

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

<?php
$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!" - correct!

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

<?php

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
           
$i++;
           
$s = 1;
          }
         
$digits[$i] .= $char; // store digit
       
} else { // not a digit
         
if ($s != 2) { // new non-digit sequence
           
$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
}

$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'));

/*
Array
(
    [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):

<?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 {
        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:

http://www.php-security.org/MOPB/MOPB-39-2007.html
troy at troyonline dot com
23-Jun-2008 05:18
Yet another deep replace function:

<?php
   
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.

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

echo "<hr />";

$subject = array(array("first", "You should eat this")
                ,array(
"second","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
fixed the problem.

cheers, tim at hysniu.com

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

<?php

       
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;
        }
?>

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 ?.');
?>

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

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

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

<?php
$match
=array("ONE","TWO","THREE");
$replace=array("TWO WORDS","MANY LETTERS","OTHER IDEAS");
$sample="ONE SAMPLE";
echo
str_replace($match,$replace,$sample);
?>

It will show: "MANY LETTERS WORDS SAMPLE"

That is, after replacing "ONE" with "TWO WORDS", process follows with next array item and it changes "TWO" with "MANY LETTERS".

str_rot13> <str_repeat
Last updated: Fri, 13 Nov 2009
 
 
show source | credits | sitemap | contact | advertising | mirror sites