Page 1 of 1

str_replace with search and replace arrays

Posted: Fri Feb 09, 2007 8:41 pm
by aos24
The current PHP manual gives the following example for str_replace:

Code: Select all

// Order of replacement 
$str    = "Line 1\nLine 2\rLine 3\r\nLine 4\n";
$order  = array("\r\n", "\n", "\r");
$replace = '<br />';
// Processes \r\n's first so they aren't converted twice. 
$newstr = str_replace($order, $replace, $str);
That's great. However, a copy of the manual that I downloaded in October 2005 does not contain this example, and doesn't mention order of replacement. So my question is: has str_replace always had this behaviour?

Posted: Fri Feb 09, 2007 9:17 pm
by Ambush Commander
No. The manual will tell you when the functionality was added: in this case, it was PHP 4.0.5.

Posted: Fri Feb 09, 2007 9:21 pm
by aos24
Thanks. But what about the "order of replacement" functionality -- i.e., the guarantee that the array elements are processed in order -- has that been in place since 4.0.5?

Posted: Fri Feb 09, 2007 9:23 pm
by Ambush Commander
The manual does not mention any change of behavior to that effect, so I would assume so. Remember: array('replace1', 'replace2', 'replace3') is equivalent to array(0 => 'replace1', 1 => 'replace2', 2 => 'replace3')