开发者

Replace same character several times with different string [duplicate]

This question already has answers here: Multiple replace (probably preg_replace) of same string with array (2 answers) Closed 7 months ago.

I have a string with the same character in it several times and I want to replace each occurrence of this character with a different string from an ar开发者_如何转开发ray. I.e. just like in prepared statements:

String: "SELECT * FROM x WHERE a = ? AND b = ?"

Array: ['alpha', 'beta']

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


If you have control over what the replacement character is, use sprintf

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

or vsprintf:

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

And even if you don't:

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


Try this:

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

See here. The fourth Parameter limits the maximum replaces per run to one instead of unlimited.


Without regex functions (as a bonus, also allows replacement of arbitrary strings, not just characters):

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;
}

Example:

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

gives:

sf sdf alphaasdf sdsbetagammmaggg
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜