note 102144 modified in function.str-replace by danbrown

From: Date: Sat, 29 Jan 2011 14:26:06 +0000
Subject: note 102144 modified in function.str-replace by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-176492@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: <?php $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: <?php 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" --was-- 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" http://php.net/manual/en/function.str-replace.php

« previous php.notes (#176492) next »