note 102144 deleted from function.str-replace by cmb

From: Date: Sun, 15 Sep 2019 14:48:40 +0000
Subject: note 102144 deleted from function.str-replace by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-212212@lists.php.net to get a copy of this message
Note Submitter: mevdschee ---- 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"

« previous php.notes (#212212) next »