note 38621 deleted from function.str-replace by felipe
| From: | felipe@php.net | Date: | Sun, 23 Mar 2008 23:04:43 +0000 |
| Subject: | note 38621 deleted from function.str-replace by felipe | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-137418@lists.php.net to get a copy of this message | ||
Note Submitter: xavier paz (xpaz at matadracs dot 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 be a problem if you only want to change the original
text.
For example, consider this code:
<?php
$search = array("one", "two", "three");
$replace = array("two", "three", "one");
$subject = "one two three";
echo str_replace($search, $replace, $subject). "<br>";
// echoes "one one one"
?>
This function makes the substitutions only to the original text.
<?php
/**
* 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:
<?php
echo str_replace_clean($search, $replace, $subject);
// echoes "two three one"
?>
-- Xavier