0

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"

2
  • What database interface are you using? It probably has this ability built-in (and it's probably more secure). Commented Aug 3, 2010 at 3:03
  • Yeah sure database interfaces have this usually built-in but I just wanted the SQL-like syntax as a example because most people know it already. There are already a couple of nice solutions here I'm just trying to figure out which one works best for me. Commented Aug 3, 2010 at 13:53

3 Answers 3

8

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");
Sign up to request clarification or add additional context in comments.

5 Comments

This might be difficult to use in a programmatic manner because the number of replacements may not be fixed. vsprintf is a better solution.
@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.
+1 vsprintf() is awesome. No idea why I'm such a huge fan of it but I just am. 8)
@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. :)
The vsprintf() version combined with str_replace() does it for me. Thanks guys. Awesome fast and good answers.
3

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.

3 Comments

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)
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).
There's the vsprintf and he could also use sprintf+call_user_func (though the last one would be awkward).
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.