用不同的字符串多次替换相同的字符

时间:2010-08-03 02:52:23

标签: php string

我有一个字符串中有相同的字符几次,我想用一个不同的字符串替换每个出现的字符。即就像准备好的陈述一样:

字符串:"SELECT * FROM x WHERE a = ? AND b = ?"
数组:['alpha', 'beta']

结果:"SELECT * FROM x WHERE a = alpha AND b = beta"

3 个答案:

答案 0 :(得分:8)

如果您可以控制替换字符的内容,请使用sprintf

sprintf('Hello %s, how %s %s?', 'World', 'are', 'you');

vsprintf

vsprintf('Hello %s, how %s %s?', array('World', 'are', 'you'));

即使你不这样做:

$str = 'Hello ?, I hope ? ?.';
$str = str_replace('?', '%s', $str);
$str = sprintf($str, "World", "you're", "fine");

答案 1 :(得分:3)

试试这个:

$str = "SELECT * FROM x WHERE a = ? AND b = ?";
$arr = array("alpha", "beta");
foreach ($arr as $s)
    $str = preg_replace("/\?/", $s, $str, 1);
echo $str;

here。第四个参数将每次运行的最大替换限制为一次而不是无限制。

答案 2 :(得分:1)

没有正则表达式函数(作为奖励,也允许替换任意字符串,而不仅仅是字符):

function replacement($string, $search, array $replacements) {
    $pos = 0;
    while (($f = strpos($string, $search, $pos)) !== FALSE) {
        $r = array_shift($replacements);
        $string = substr($string, 0, $f) . $r .
            substr($string, $f + strlen($search));
       $pos = $f + strlen($r);
    }
    return $string;
}

示例:

echo replacement("sf sdf aaasdf sdsaaaaggg", "aa",
    array("alpha", "beta", "gammma"));

给出:

sf sdf alphaasdf sdsbetagammmaggg