簡體   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