举个例子给你看看是不是你想要的。
有个字符串“abcadeafg”,把其中的三个字母a分别替换成x,y,z:
$pattern = array('/a/', '/a/', '/a/');
$replacement = array('x', 'y', 'z');
$subject = 'abcadeafg';
$res = preg_replace($pattern, $replacement, $subject , 1);
echo $res; // xbcydezfg
Example #2 preg_replace()中使用基于索引的数组
$string = 'The quick brown fox jumped over the lazy dog.';
$patterns = array();
$patterns[0] = '/quick/';
$patterns[1] = '/brown/';
$patterns[2] = '/fox/';
$replacements = array();
$replacements[2] = 'bear';
$replacements[1] = 'black';
$replacements[0] = 'slow';
echo preg_replace($patterns, $replacements, $string);
?>
以上例程会输出:
The bear black slow jumped over the lazy dog.
对模式和替换内容按key进行排序我们可以得到期望的结果。
ksort($patterns);
ksort($replacements);
echo preg_replace($patterns, $replacements, $string);
?>
以上例程会输出:
The slow black bear jumped over the lazy dog.
Example #3 替换一些值
$patterns = array ('/(19|20)(\d{2})-(\d{1,2})-(\d{1,2})/',
'/^\s*{(\w+)}\s*=/');
$replace = array ('\3/\4/\1\2', '$\1 =');
echo preg_replace($patterns, $replace, '{startDate} = 1999-5-27');
?>
以上例程会输出:
$startDate = 5/27/1999
细细的看下str_replace
你可以给个例子先 要不然 很难明白你遇到的是什么问题, 想要什么结果