Note Submitter: zgardner at allofe dot com
----
If you're using an array for $search and have elements that are substrings of other elements, make sure that you place the longer strings at the beginning of the array.
The following is a snippet where I wanted to replace all combinations of returns with a BR tag.
<?
$search = array("\n", "\r", "\n\r", "\r\n");
$replace = "<BR>";
$some_string = "abc \n def \r hij \n\r klm \r\n nop";
echo str_replace($search, $replace, $some_string); // INCORRECT: Echos "abc <BR> def <BR> hij <BR><BR> klm <BR><BR> nop"
$search_correct = array("\n\r", "\r\n", "\n", "\r");
echo str_replace($search_correct, $replace, $some_string); // CORRECT: Echos "abc <BR> def <BR> hij <BR> klm <BR> nop"
?>
In the first echo, the string "\n\r" is being replaced by "\n" then by "\r" instead of being matched with "\n\r". When the order is changed in the second echo to have the longer strings before the less specific ones, everything goes peachy.
My two guesses as to what is internally happening is that either PHP loops over $search and calls str_replace for each element, or PHP uses first match instead of best match (longest match) replacement for efficiency reasons.
lmpx.com only provides a reader for public news (NNTP) servers. It is not
affiliated with the servers or forums shown here and is not responsible for
the content of articles, which is written by their respective authors.