繁体   English   中英

如何用变量数组替换单个字符的多次出现

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

This is a? ?.

我有上面的字符串。 我想用这个数组中的变量替换问号:

array('test', 'phrase');

对于最终结果:

This is a test phrase.

如何在 PHP 中完成此操作?

您可以使用vsprintf

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

如果你只有?,然后替换? 对于 %s:

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

这是一个非常简洁的解决方案:

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

$in现在是最后一个字符串。

注释:

  • 如果问号多于数组元素,则保留多余的问号
  • 如果数组元素多于问号,则只使用需要的元素
  • 要在最后的字符串中添加问号,请输入'?' 在你的数组中替换

示例: http://codepad.org/TKeubNFJ

来吧,写一个始终有效的 function 有多难? 到目前为止发布的所有答案都将为以下输入字符串和替换值提供不正确的结果:

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

一个经常被忽视的问题是,如果您更改输入字符串,包含原始输入模式的替换值可能会再次被替换。 要解决这个问题,您应该完全构建一个新字符串。 此外,sprintf 解决方案(可能不正确)假设输入字符串从不包含“%s”。 原始发帖人从未说过是这样的,所以'%s'应该独自一人。

试试这个 function。 它可能不是最快也不是最优雅的解决方案,但至少它给出了明智的(嗯)output 结果,无论输入如何。

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

这个怎么样:

$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);

在 ideone.com 上运行示例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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