Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

str_replace

(PHP 3 >= 3.0.6, PHP 4, PHP 5)

str_replace --  Заменяет строку поиска на строку замены

Описание

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

Эта функция возвращает строку или массив subject, в котором все вхождения search заменены на replace. Если не нужны сложные правила поиска/замены, использование этой функции предпочтительнее ereg_replace() или preg_replace().

С версии PHP 4.0.5, любой аргумент str_replace() может быть массивом.

Внимание

В версиях младше 4.3.3 эта функция содержит ошибку при одновременной передаче массивов в аргументах search и replace. Ошибка заключается в том, что пустые элементы массива search пропускались без перемещения к следующему элементу массива replace. Эта ошибка была исправлена в PHP 4.3.3. Если ваши скрипты использовали эту ошибку, то в них нужно удалить пустые элементы из массива search перед вызовом этой функции.

Если subject - массив, поиск и замена производится в каждом элементе этого массива, и возвращается также массив.

Если и search, и replace - массивы, то str_replace() использует все значения массива search и соответствующие значения массива replace для поиска и замены в subject. Если в массиве replace меньше элементов, чем в search, в качестве строки замены для оставшихся значений будет использована пустая строка. Если search - массив, а replace - строка, то replace будет использована как строка замены для каждого элемента массива search.

Пример 1. Примеры использования str_replace()

<?php
// присваивает <body text='black'>
$bodytag = str_replace("%body%", "black", "<body text='%body%'>");

// присваивает: 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);

// начиная с версии 5.0.0 доступен аргумент count
$str = str_replace("ll", "", "good golly miss molly!", $count);
echo
$count; // 2
?>

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

Замечание: Начиная с PHP 5.0.0 количество произведенных замен может быть получено в необязательном аргументе count, который передается по ссылке. В версиях до PHP 5.0.0 этот аргумент недоступен.

См. также описание функций str_ireplace(), substr_replace(), ereg_replace(), preg_replace() и strtr().



str_rot13> <str_repeat
Last updated: Sat, 27 Jan 2007
 
add a note add a note User Contributed Notes
str_replace
jmack at parhelic dot com
01-Nov-2007 05:16
The ReplaceOne function above does not work properly in all cases. (Not even using the provided example.)

Here is my replacement:

function str_replace_once($search, $replace, $subject)
{
    if(($pos = strpos($subject, $search)) !== false)
    {
        $ret = substr($subject, 0, $pos).$replace.substr($subject, $pos + strlen($search));
    }
    else
    {
        $ret = $subject;
    }
   
    return($ret);
}
Howard Yeend: http://www.puremango.co.uk
26-Oct-2007 02:52
<?php

/*
a function to replace *all* occurrences of $search
(aka recursive str_replace)

echo str_replace("--","-","a-b--c---d------e");
->returns [a-b-c--d---e]

echo str_replace_all("--","-","a-b--c---d------e")."<br />";
->return [a-b-c-d-e]

*/

function str_replace_all($search,$replace,$subject) {
  while(
strpos($subject,$search)!==false) {
   
$subject = str_replace($search,$replace,$subject);
  }
  return
$subject;
}

echo
str_replace("--","-","a-b--c---d------e")."<br />";
echo
str_replace_all("--","-","a-b--c---d------e")."<br />";
?>
Hayley Watson
16-Oct-2007 04:34
In response to php at azulmx dot com's comment (03-10-2007):
"If your replace string results from an expression or a function, str_replace will evaluate/call it even if the search string is not found."

This is true for ANY function, not just str_replace: the argument expressions are evaluated, and the results are then passed to the function being called.
<?php
$result
= str_replace ("zzz", am_i_called (), "this string does not contain the search string");
?>
Is functionally identical to
<?php
$search
= "zzz";
$replace = am_i_called();
$string = "this string does not contain the search string";
$result = str_replace($search, $replace, $string);
?>
(except of course for the use of three additional variables!)

This is the main reason why the comma operator is shown as having such low precedence - everything around them has to be evaluated first. And with the parentheses around the argument list, those arguments are evaluated first before the expression that contains the parenthesised expression (i.e., the function call) can be evaluated.
mhabr at centrum dot cz
16-Oct-2007 04:00
function str_ireplace (case sensitive) fro PHP 4 and lower

function str_ireplace($search,$replace,$subject) {
$search = preg_quote($search, "/");
return preg_replace("/".$search."/i", $replace, $subject); }
hinom [at] hotmail [dot] co [dot] jp
03-Oct-2007 10:32
recursive e case-insensitive str_replace for php users under 5 version

stripos() function is available in php5, therefore needed create generic function stripos2()

hope this help many users

best regards for all PHP!

thnks for zend and php developers

<?php

$find  
= "script"; // string to search
$new    = "##";     // string to replace
// text
$string = "33onSCRIPTon oano AoKO k SCRIPT--atooto Atoto SCRIPTmoomo lko KOx0 lolo POpopo";

    function
stripos2($string,$word){
       
$retval   = false;
       
$word_len = strlen($word);
        for(
$i=0;$i<=strlen($string);$i++){
            if (
strtolower(substr($string,$i,$word_len)) == strtolower($word)){
               
$retval[0] = true;
               
$retval[1] = $i;
               
$retval[2] = $word_len;
            }
        }
        return
$retval;
    }

    function
striReplace( $string, $find, $new ){
       
$r  = false;
        while(
$p = stripos2( $string, $find ) ){
            if(
$p[0] ){
               
$r  = substr( $string, 0, $p[1] );
               
$r .= $new;
               
$r .= substr( $string, $p[1] + $p[2] );
            }
           
$string = $r;
        }
        return
$r;
    }

    echo
'original:<br />' . $string . '<hr>';

    echo
striReplace( $string, $find, $new );
?>
php at azulmx dot com
02-Oct-2007 07:31
If your replace string results from an expression or a function, str_replace will evaluate/call it even if the search string is not found.

function am_i_called ()
{
  echo "oh no, i am<br>";
  return "";
}

str_replace ("zzz", am_i_called (), "this string does not contain the search string");

str_replace ("zzz", $result = "rats!", "this string does not contain the search string");

echo "$result<br>";

// oh no, i am
// rats!

also it isn't re-evaluated for multiple replacements...

echo str_replace ("zzz", $result = "r".$result, "zzz zzz zzz zzz zzz zzz zzz");

// rrats! rrats! rrats! rrats! rrats! rrats! rrats!
marc at palaueb dot com
24-Sep-2007 01:44
I'm searching for a function who replace the last occurrence of a string but I have not found anything.

Check this out:

function str_rreplace($search,$replace,$subject){
    $strrpos=strrpos($subject,$search);
    return substr_replace($subject,$replace,$strrpos,strlen($search));
}

the only one problem is that do not have a limit to replace, just replace the last occurrence.
japxrf at mizzou dot edu
14-Sep-2007 09:34
I thought this might be handy for someone.

I'm working with a CSV file and noticed that excel tends to put extra quotes around portions of lines that are misformatted. I needed a way to get the section of a line that is surrounded by quotes, remove the quotes and the commas inside those quotes, then put it back into the line.

Don't knock the code - I'm a novice :)

//assuming here that your current line from CSV file is $data2
if(stristr($data2, '"')){ //if there's a quote in this line it needs fixin'
            $quotepos = strpos($data2, '"');
            $quotepos_end = strrpos($data2, '"');
            $str_len = $quotepos_end - $quotepos;
            $badquote = substr($data2, $quotepos, $str_len+1);
            $badquote2 = str_replace('"',"",$badquote);
            $badquote3 = str_replace(",","",$badquote2);
            $data2 = str_replace($badquote, $badquote3, $data2);
}
Guy Gordon
09-Sep-2007 04:20
The exact meaning of "all occurrences" should be documented.  Str_replace does not include any replaced text in subsequent searches.    (The search for the next occurrence starts after the replace, not at the beginning of the string.)  This can lead to the result string retaining occurrences of the search string.

For example, if you want to replace all multiple spaces with a single space, a simple str_replace will not work:

  $strIn = '      ';     //six spaces
  echo str_replace('  ',' ',$strIn);  //will echo three spaces

Instead, you could use:

  while (strpos($strIn,'  ') !== False)
    $strIn = str_replace('  ',' ',$strIn);
molokoloco at gmail dot com
05-Sep-2007 05:40
function clean($string) {
    $bad = array('\’', '&rsquo;', '…', '&hellip;');
    $good = array('\'', '\'', '...', '...');
    $string = str_replace($bad, $good, $string);
}

// The result seem to have a bug...
print_r(clean('totot@toto.com'));

//=> totot@toto…com
gomodo at free dot fr
01-Sep-2007 01:30
Some controls problems when you want to replace backslashes '\' ?

Look this example and the protected functions (we try to replace '\' by '.') :

<?php
   
//****** test with bad double-quote parameter
   
test_replace_backslash("abcde\2fghij",".");
   
//******
   
echo "\n";
   
//****** test with good simple-quote parameter
   
test_replace_backslash('abcde\2fghij',".");
   
//**************************************

    //************ functions ****************
   
function test_replace_backslash($str_test,$str_replace)
    {
       
$str_new= replace_backslash($str_test,".");
        if (!
$str_new) echo "no readable char found - control call with 'string' and not ".'"'."string".'"';
        else echo
$str_new;
    }
   
//*****
   
function replace_backslash($str_to_detect,$str_replace)
    {
        if(
chrs_is_all_readable($str_to_detect)) {
            return(
preg_replace('[\\\]',$str_replace,$str_to_detect));
        }
        return (
false);
    }
   
//***** inspired from http://fr.php.net/manual/fr/function.chr.php#70931
    //***** ( thank to "jgraef at users dot sf dot net")
   
function chrs_is_all_readable($string)
    {
      for (
$i=0;$i<strlen($string);$i++)
        {
           
$chr = $string{$i};
           
$ord = ord($chr);
            if (
$ord<32 or $ord>126) return(false);
        }
      return (
true);
    }

?>

this example return :

no readable char found - control call with 'string' and not "string"
abcde.2fghij
David Gimeno i Ayuso (info at sima dot cat)
09-Aug-2007 12:50
This is the functions I wrote for the problem reported above, str_replace in multi-dimensional arrays. It can work with preg_replace as well.

function array_replace($SEARCH,$REPLACE,$INPUT) {
  if (is_array($INPUT) and count($INPUT)<>count($INPUT,1)):
    foreach($INPUT as $FAN):
      $OUTPUT[]=array_replace($SEARCH,$REPLACE,$FAN);
    endforeach;
  else:
    $OUTPUT=str_replace($SEARCH,$REPLACE,$INPUT);
  endif;
  return $OUTPUT;
}
David Gimeno i Ayuso (info at sima dot cat)
09-Aug-2007 12: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 )

?>
mjaque at ilkebenson dot com
22-Jul-2007 01:28
In order to replace carriage return characters from form inputs, if everything else fails, you can try:

<?php
$new_text
= str_replace(chr(13).chr(10), '_', $original_text);
?>

And in order to show the line feeds in a javascript alert, you can do:

<?php
$new_text
= str_replace(chr(13).chr(10), '\n', $original_text);
?>
the-master at supanet dot com
17-Jul-2007 11:40
I get annoyed when double triple and more spaces in a row get in the way of my code as they count as characters in wordwrap and therefore ruin the look of the page as the spaces wont show up to the user but the writing look uneaven as the wordwraping has counted the spaces so this might help someone else having this problem.  Pretty simple but should work.

<?php
while(strpos($string, "  ")) {
$string = str_replace("     ", " ", $string); }
?>

Simple but effective code.
tom at appee dot com
09-Jul-2007 10:32
Note that the $replace parameter is only evaluated once, so if you have something like:

<?php
$item
= 1;
$list = str_replace('<li>', $item++.'. ', $list);
?>

then every "li" tag in the input will be replaced with "1. ".
Aaron at xavisys dot com
03-Jul-2007 03:46
In case anyone doesn't know, Erik's code will not work.  Besides the major syntax flaws, the count parameter returns how many replacements were made, it DOES NOT limit how many are made.  If you really need to replace every other occurrence, this DOES work:
<?php
function str_replace_every_other($needle, $replace, $haystack, &$count=null, $replace_first=true) {
   
$count = 0;
   
$offset = strpos($haystack, $needle);
   
//If we don't replace the first, go ahead and skip it
   
if (!$replace_first) {
       
$offset += strlen($needle);
       
$offset = strpos($haystack, $needle, $offset);
    }
    while (
$offset !== false) {
       
$haystack = substr_replace($haystack, $replace, $offset, strlen($needle));
       
$count++;
       
$offset += strlen($replace);
       
$offset = strpos($haystack, $needle, $offset);
        if (
$offset !== false) {
           
$offset += strlen($needle);
           
$offset = strpos($haystack, $needle, $offset);
        }
    }
    return
$haystack;
}

//Use it like this:
$str = "one two one two one two";
echo
str_replace_every_other('one', 'two', $str, $count).'<br />';
//two two one two two two
echo str_replace_every_other('one', 'two', $str, $count, false).'<br />';
//one two two two one two
?>
I added the last option ($replace_first) to let you replace the odd occurrences (true, default) or the evens (false).
Eric
15-Jun-2007 04:11
i made this function for http://www.linksback.org it replaces every other occurrence

<?php
function str_replace_every_other($needle, $replace, $haystack) {
   
$ii=0
 
while ( str_replace("$needle", "$replace", "$haystack", 1) {
  while (
str_replace("$needle", "tttttttttt", "$haystack", 1) {  
      
$ii++;
  }
}
str_replace("tttttttttt", "$needle","$haystack");  
}

?>
cm at k-a-p dot com
12-Jun-2007 06:47
Here is a version that allows for empty multidimensional arrays:

function str_replace_array ($search, $replace, $subject) {
    if (is_array($subject)) {
        foreach ($subject as $id=>$inner_subject) {
            $subject[$id]=str_replace_array($search, $replace, $inner_subject);
        }
    } else {
        $subject=str_replace($search, $replace, $subject);
    }
    return $subject;
}
tim at hysniu dot com
05-Jun-2007 11: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);
}

?>
yakasha
07-May-2007 02:01
As the documentation states, remember that arrays are processed in order, take care to not replace your replacements:

<?php
$s
= 'apple\'s';
$f = array('\'', '\\');
$r = array('\\\'', '\\\\');
echo
str_replace($f, $r, $s);  // Produces:  apple\\'s

$f = array('\\', '\'');
$r = array('\\\\', '\\\'');
echo
str_replace($f, $r, $s); // Produces:  apple\'s
?>
patrick at rocksolidsystems dot biz
22-Mar-2007 02:30
With reference to the google type searches above ...

This is a case insensitive replace....

This code below will highlight the "found" text in red and return the string unaltered (in terms of case).

<?php
function turn_red($haystack,$needle)
{
    
$h=strtoupper($haystack);
    
$n=strtoupper($needle);
    
$pos=strpos($h,$n);
     if (
$pos !== false)
         {
       
$var=substr($haystack,0,$pos)."<font color='red'>".substr($haystack,$pos,strlen($needle))."</font>";
       
$var.=substr($haystack,($pos+strlen($needle)));
       
$haystack=$var;
        }
     return
$haystack;
}
?>
quentin (dot) t (at) gmail (dot) com
04-Mar-2007 02:31
A little enhancement to heavyraptor's replace_accents (simply adding 'cedil' and 'ring' character variations) :

<?php
function replace_accents($s) {
   
$s = htmlentities($s);
   
$s = preg_replace ('/&([a-zA-Z])(uml|acute|grave|circ|tilde|cedil|ring);/', '$1', $s);
   
$s = html_entity_decode($s);
    return
$s;
}
?>

Cheers.
kole
25-Feb-2007 05: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 12: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."
juli at poblenou dot com
14-Feb-2007 02:56
The function works with arrays (as stated) provided those are unidimensional arrays.
In case you use multidimensional arrays, it won't replace anything, at least in PHP 4.4. If you need to work with multidimensional arrays, you should iterate (using foreach) over every unidimensional array.
15-Jan-2007 01: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.
Boris DOT Christ AT laposte DOT net
27-Nov-2006 01:32
I create a little function to transform (to example) "User@example.net" in "user AT example DOT net" and conversely.

<?php
function code_mail($email) {
    if(
preg_match('`^.+@.+\..{1,5}$`', $email)) { //email format
       
$email = str_replace('.', ' DOT ', $email); //replace . by dot
       
$email = str_replace('@', ' AT ', $email); //replace @ by at
       
return $email;
    }       
    else {
//not email format
       
return false;
    }
}
function
decode_mail($email) { //on d
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com
Z058440144362 Z348613067571