简体   繁体   中英

How can I replace multiple occurrences of a single character with an array of variables

This is a? ?.

I have the above string. I want to replace the question marks with variables from this array:

array('test', 'phrase');

For a final result of:

This is a test phrase.

How can I accomplish this in PHP?

You can use vsprintf :

vsprintf("This is a %s %s.", array("test", "phrase")); // "This is a test phrase."

If you only have?, then substitute the? for %s:

$str = "This is a ? ?.";   
vsprintf(str_replace("?", "%s", $str), array("test", "phrase"));

Here's a very concise solution:

$in = 'This is a ? ?.';
$ar = array('test', 'phrase');
foreach ($ar as $rep)
    $in = implode($rep, explode('?', $in, 2));

$in is now the final string.

Comments:

  • if there are more question marks than array elements, the excess question marks remain
  • if there are more array elements than question marks, only those needed will be used
  • to put a question mark in your final string, put a '?' substitution in your array

Example: http://codepad.org/TKeubNFJ

Come on people, how hard is it to write a function that always works? ALL of the answers posted so far will give incorrect results for the following input string and replacement values:

$in="This i%s my ? input ? string";
$replace=array("jo%shn?",3);

One often-overlooked problem is that if you change the input string, replacement values containing the original input pattern might be replaced again. To solve this, you should build a new string altogether. Also, the sprintf solutions make the (possibly incorrect) assumption that the input string never contains '%s'. The original poster never said that that was the case, so '%s' should be left alone.

Try this function instead. It might not be the fastest nor most elegant solution, but at least it gives sensible (ahum) output results regardless of the input.

function replace_questionmarks($in,$replace)
{
    $out=""; 
    $x=0;
    foreach (explode("?",$in) as $part) 
    {
        $out.=$part;
        $out.=$replace[$x++];
    }
    return $out;
}

$in="This i%s my ? input ? string";
$replace=array("jo%shn?",3);
print replace_questionmarks($in,$replace);

Output:

This i%s my jo%shn? input 3 string

How about this:

$str = 'This is a ? ?.';

$replacement = array('test', 'phrase');

foreach ($replacement as $word) {
    if (($pos = strpos($str, '?')) !== false) {
        $str = substr_replace($str, $word, $pos, 1);
    }
}

var_dump($str);

Running sample on ideone.com

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM