str_replace with search and replace arrays

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
aos24
Forum Newbie
Posts: 9
Joined: Tue Feb 06, 2007 4:37 pm

str_replace with search and replace arrays

Post 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?
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post by Ambush Commander »

No. The manual will tell you when the functionality was added: in this case, it was PHP 4.0.5.
aos24
Forum Newbie
Posts: 9
Joined: Tue Feb 06, 2007 4:37 pm

Post 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?
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post 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')
Post Reply