preg_replace使用foreach循环在数组中的多个字符串

时间:2014-08-14 13:47:42

标签: php mysql arrays

        $message_detected  = "#A# #B#";
  Array ( [0] => Array ( [0] => 923126812536 [1] => Mudassar [2] => Kasur ) 
        [1] => Array ( [0] => 923006542399 [1] => Zubair [2] => Lahore ) );

有2个阵列

foreach ($array as $new){
$find =    array('/#A#/',   '/#B#/',  '/#C#/',   '/#D#/',   '/#E#/',    '/#F#/',     '/#G#/',    '/#H#/',     '/#I#/',    '/#J#/',     '/#K#/',     '/#L#/',     '/#M#/',     '/#N#/',      '/#O#/',      '/#P#/',     '/#Q#/',      '/#R#/',     '/#S#/',       '/#T#/',     '/#U#/',      '/#V#/',      '/#W#/',       '/#X#/',      '/#Y#/',     '/#Z#/');//26
$replace = array($new[1],   $new[2],  $new[3],   $new[4],   $new[5],    $new[6],     $new[7],     $new[8],     $new[9],    $new[10],    $new[11],    $new[12],    $new[13],    $new[14],     $new[15],     $new[16],    $new[17],    $new[18],     $new[19],     $new[20],     $new[21],     $new[22],     $new[23],     $new[24],      $new[25],   $new[26]);
$message_detected = preg_replace($find, $replace, $message_detected);
 //Message should be change each time despit of only first

echo "Messsage :". $message_detected."</br></br></br></br>";    

}

结果应该是

消息:Mudassar Kasur

消息:Zubair Lahore

但它显示

消息:Mudassar Kasur

消息:Mudassar Kasur

请指导我错在哪里。以及如何获得必需结果

1 个答案:

答案 0 :(得分:0)

你在每个循环上覆盖你的变量。它应该是另一个:

$template  = "#A# #B# #C#";
$values = array (
    array ( 923126812536, 'Mudassar', 'Kasur'),
    array ( 923006542399, 'Zubair',   'Lahore'),
);

$vars = array('#A#', '#B#','#C#','#D#');
foreach($values as $lst) {
    $result = str_replace($vars, $lst, $template);
    echo $result, "\n";
}

(为了便于阅读,我更改了变量名称。)