note 97989 added to function.str-replace

From: Date: Wed, 19 May 2010 18:12:38 +0000
Subject: note 97989 added to function.str-replace
Groups: php.notes 
Request: Send a blank email to php-notes+get-169417@lists.php.net to get a copy of this message
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. ---- Server IP: 69.147.83.197 Probable Submitter: 70.129.225.173 ---- Manual Page -- http://www.php.net/manual/en/function.str-replace.php Edit -- https://master.php.net/note/edit/97989 Del: integrated -- https://master.php.net/note/delete/97989/integrated Del: useless -- https://master.php.net/note/delete/97989/useless Del: bad code -- https://master.php.net/note/delete/97989/bad+code Del: spam -- https://master.php.net/note/delete/97989/spam Del: non-english -- https://master.php.net/note/delete/97989/non-english Del: in docs -- https://master.php.net/note/delete/97989/in+docs Del: other reasons-- https://master.php.net/note/delete/97989 Reject -- https://master.php.net/note/reject/97989 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#169417) next »