views:

54

answers:

3

Hello,

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 array. 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"

Is there any way to do that?

+3  A: 

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.

XQYZ
It might be because I think regular expression is devil magic, but does this not seem just a little obtuse? Seeing as modifying the parameter of the question just a little bit makes it much more solution overall. (See sprintf)
Mark Tomlin
Yes, you are probably right, sprintf will most likely be sufficient for the purpose of the author. However, it does not use an Array as it was specified in the original question, which makes this a more generic approach (say you need the array).
XQYZ
@XQYZ There's the `vsprintf` and he could also use `sprintf`+`call_user_func` (though the last one would be awkward).
Artefacto
+7  A: 

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");
deceze
This might be difficult to use in a programmatic manner because the number of replacements may not be fixed. [`vsprintf`](http://www.php.net/manual/en/function.vsprintf.php) is a better solution.
Artefacto
Good point, depends on how it's supposed to be used.
deceze
@deceze well, he specifically says "from an array", though I concede the OPs frequently point halfway to a solution that doesn't really address their underlying problem.
Artefacto
+1 `vsprintf()` is **awesome**. No idea why I'm such a huge fan of it but I just am. 8)
BoltClock
@Artefacto I prefer to point OPs in the right direction and let them sort out the syntactical details themselves, unless the question is about syntax. :)
deceze
The vsprintf() version combined with str_replace() does it for me. Thanks guys. Awesome fast and good answers.
Wolax
+1  A: 

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
Artefacto