note 102144 added to function.str-replace
| From: | mevdschee at osu1 dot php dot net | Date: | Sat, 29 Jan 2011 11:19:46 +0000 |
| Subject: | note 102144 added to function.str-replace | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-176489@lists.php.net to get a copy of this message | ||
say you want every "a" replaced by "abba" and every "b" replaced by
"baab" in the string "ab" you do:
$search = array("a","b");
$replace = array("abba","baab");
echo str_replace($search,$replace,"ab");
that results in "abaabbaababaab" and not the expected "abbabaab"
I wrote this little snippet to solve the replacements-in-replacement problem:
function search_replace($s,$r,$sql)
{ $e = '/('.implode('|',array_map('preg_quote', $s)).')/';
$r = array_combine($s,$r);
return preg_replace_callback($e, function($v) use ($s,$r) { return $r[$v[1]]; },$sql);
}
echo search_replace($search,$replace,"ab");
that results in the expected "abbabaab"
----
Server IP: 213.249.64.162
Probable Submitter: 81.68.128.79
----
Manual Page -- http://www.php.net/manual/en/function.str-replace.php
Edit -- https://master.php.net/note/edit/102144
Del: integrated -- https://master.php.net/note/delete/102144/integrated
Del: useless -- https://master.php.net/note/delete/102144/useless
Del: bad code -- https://master.php.net/note/delete/102144/bad+code
Del: spam -- https://master.php.net/note/delete/102144/spam
Del: non-english -- https://master.php.net/note/delete/102144/non-english
Del: in docs -- https://master.php.net/note/delete/102144/in+docs
Del: other reasons-- https://master.php.net/note/delete/102144
Reject -- https://master.php.net/note/reject/102144
Search -- https://master.php.net/manage/user-notes.php