note 97989 deleted from function.str-replace by danbrown

From: Date: Wed, 19 May 2010 18:43:29 +0000
Subject: note 97989 deleted from function.str-replace by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-169418@lists.php.net to get a copy of this message
Note Submitter: zgardner at allofe dot com ---- If you're using an array for $search and have elements that are substrings of other elements, make sure that you place the longer strings at the beginning of the array. The following is a snippet where I wanted to replace all combinations of returns with a BR tag. <? $search = array("\n", "\r", "\n\r", "\r\n"); $replace = "<BR>"; $some_string = "abc \n def \r hij \n\r klm \r\n nop"; echo str_replace($search, $replace, $some_string); // INCORRECT: Echos "abc <BR> def <BR> hij <BR><BR> klm <BR><BR> nop" $search_correct = array("\n\r", "\r\n", "\n", "\r"); echo str_replace($search_correct, $replace, $some_string); // CORRECT: Echos "abc <BR> def <BR> hij <BR> klm <BR> nop" ?> In the first echo, the string "\n\r" is being replaced by "\n" then by "\r" instead of being matched with "\n\r". When the order is changed in the second echo to have the longer strings before the less specific ones, everything goes peachy. My two guesses as to what is internally happening is that either PHP loops over $search and calls str_replace for each element, or PHP uses first match instead of best match (longest match) replacement for efficiency reasons.

« previous php.notes (#169418) next »