note 91536 modified in function.str-replace by danbrown

From: Date: Tue, 16 Jun 2009 13:44:43 +0000
Subject: note 91536 modified in function.str-replace by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-156917@lists.php.net to get a copy of this message
Be careful when replacing characters (or repeated patterns in the FROM and TO arrays): For example: <?php $arrFrom = array("1","2","3","B"); $arrTo = array("A","B","C","D"); $word = "ZBB2"; echo str_replace($arrFrom, $arrTo, $word); ?> I would expect as result: "ZDDB" However, this return: "ZDDD" (Because B = D according to our array) To make this work, use "strtr" instead: <?php $arr = array("1" => "A","2" => "B","3" => "C","B" => "D"); $word = "ZBB2"; echo strtr($word,$arr); ?> This returns: "ZDDB" --was-- Be careful when replacing characters (or repeated patterns in the FROM and TO arrays): For example: $arrFrom = array("1","2","3","B"); $arrTo = array("A","B","C","D"); $word = "ZBB2"; echo str_replace($arrFrom, $arrTo, $word); I would expect as result: "ZDDB" However, this return: "ZDDD" (Because B = D according to our array) To make this work, use "strtr" instead: $arr = array("1" => "A","2" => "B","3" => "C","B" => "D"); $word = "ZBB2"; echo strtr($word,$arr); This returns: "ZDDB" http://php.net/manual/en/function.str-replace.php

« previous php.notes (#156917) next »