note 38505 deleted from function.str-replace by nlopess
| From: | nlopess@php.net | Date: | Wed, 24 Dec 2003 17:45:48 +0000 |
| Subject: | note 38505 deleted from function.str-replace by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-62430@lists.php.net to get a copy of this message | ||
Note Submitter: xavier paz (xpaz@matadracs.com)
----
If both the search and replace params are arrays, str_replace() will apply the substitutions
incrementally, it is, it will try the first substitution, then the second using the result from the
first one, and so on. It may be OK, or it may also be a big problem if you only want to change the
original text.
For example, consider this code:
$search = array("one", "two", "three");
$replace = array("two", "three", "one");
$subject = "one two three";
str_replace() replaces incrementally:
echo str_replace($search, $replace, $subject). "<br>";
// echoes "one one one"
This function makes the substitutions only to the original text.
/**
* same as str_replace (array, array, string), but changing only the text in the
* original string
* $search and $replace are arrays of strings, $subject is a string
*/
function str_replace_clean ($search, $replace, $subject) {
if (!is_array($search) or !is_array($replace) or !is_string($subject)) return $subject;
while (count($search)) {
// get current terms, reduce the arrays for the next iteration
$search_text = array_shift($search);
$replace_text = array_shift($replace);
// check if the substring is present
$pos = strpos($subject, $search_text);
if (is_int($pos)) {
// match found - break in pieces
$pieces = explode($search_text, $subject);
if (count($search)) { // only if there are more substitutions to do
// make next substitutions in every piece of text between matches
foreach ($pieces as $k => $v) {
if (strlen($v)) $pieces[$k] = str_replace_clean($search, $replace, $v);
}
}
$subject = join($replace_text, $pieces);
break;
}
}
return $subject;
}
To test:
echo str_replace_clean($search, $replace, $subject);
// echoes "two three one"
-- Xavier