Home > Article > Backend Development > php -str_replace没法遍历替换
php -str_replace无法遍历替换
见如下代码
$data = array('or','my','you','which','love');
$arr = array('l'=>'k','w'=>'q','e'=>'r','t'=>'y','m'=>5);
foreach ($data as $k => $v) {
foreach ($arr as $key => $value) {
$pattern = $key;
$replacment = $value;
$data[$k] = str_replace($pattern,$replacment,$v);//无法替换??
// $data[$k] = str_replace(array_keys($arr),$arr,$v);
// $data[$k] = str_replace('l','k',$v);
}
}
var_dump($data);
?>
------解决思路----------------------
不知道楼主说的替换指的是不是把data里面每个字符串中出现过的字符都去arr里面去匹配下,有的换就替换。如果是这样的话 直接这样写就可以了:
<br /><?php<br />$data = array('or','my','you','which','love');<br />$pattern = array('l','w','e','t','m');<br />$arr = array('k','q','r','y',5);<br />$newdata = str_replace($pattern, $arr, $data);<br />var_dump($newdata);<br />?><br />
0 or<br />or<br />or<br />or<br />or<br />or<br />1 my<br />my<br />my<br />my<br />my<br />5y<br />2 you<br />you<br />you<br />you<br />you<br />you<br />3 which<br />which<br />qhich<br />which<br />which<br />which<br />4 love<br />kove<br />love<br />lovr<br />love<br />love<br />