[英]Replacing tokens in a string from an array
假設我有一個字符串
$ 0是$ 2 $ 1。 仍然,\\ $ 3可以為一只小狗付出很多。
和一系列的替代品
array('puppy', 'cute', 'ridiculously', '1300')
用數組中的相應項替換字符串中的標記的最干凈方法是什么,讓我用反斜杠轉義標記字符(在本例中$
)? 我還想用空字符串替換不匹配的標記。
foreach ($array AS $key => $value)
{
$string = str_replace('$' . $key, $value, $string);
}
$test_sub= 'This $0 is $2 $1. Still, \$$3 is a lot to pay for a puppy.';
$GLOBALS['replacers'] = array('puppy', 'cute', 'ridiculously', '1300');
echo preg_replace_callback('/[^\$]\$([0-9])+/',
create_function(
'$matches',
'return $matches[0][0] . $GLOBALS[\'replacers\'][$matches[1]];'
),
$test_sub
);
這是如何完成的POC。 一個簡單的正則表達式和一個用於替換的回調。 實際的實現方式取決於您實際要使用的功能。 希望對您有所幫助。
我猜你的意思是“ \\ $ 3”,而不是“ \\ $$ 3”
preg_replace('~(?<!\\\\)\$(\d+)~e', 'isset($array[$1])?$array[$1]:""', $source);
順便說一句,您是否知道sprintf也允許編號的參數( http://php.net/manual/en/function.sprintf.php示例3)
這是一個版本。
$replacements = array('puppy', 'cute', 'ridiculously', '1300');
$input = 'This $0 is $2 $1. Still, \$3 is a lot to pay for a puppy.';
$output = preg_replace_callback('/(?<!\\\\)\$(\d+)/', 'replace_input', $input);
echo $input . "<br>";
echo $output;
function replace_input($matches) {
global $replacements;
$index = $matches[1];
return $index < 0 || $index >= count($replacements) ? $matches[0] : $replacements[$index];
}
輸出:
This $0 is $2 $1. Still, \$3 is a lot to pay for a puppy.
This puppy is ridiculously cute. Still, \$3 is a lot to pay for a puppy.
它在$之前處理反斜杠以轉義該變量。 這可能是一個笨拙的語法,因為這時您需要轉義反斜杠,這會使它進一步復雜化(在這種情況下不會處理)。 只要$不以反斜杠開頭(使用負向后 ),則正則表達式基本上表示$后跟一個或多個數字。
它對替換數組使用全局變量。 有兩種替代方法:
create_function()
。 但是我認為全局是更簡單和“全局”的,除非您有充分的理由做一些不同的事情,盡管我們對此事通常感到厭惡。
該解決方案遵循問題,並從Josh Leitzel的答案中借鑒了一點點。 不匹配的模式(例如$ 4,$ 5)將替換為空字符串,並將其從輸入中刪除。
$input = "This $0 is $2 $1. Still, \$$3 is a lot to pay for a puppy.";
$replacements = array('puppy','cute','ridiculously','1300');
$pattern = "/[$]{1}([0-9]{1})/";
preg_match_all($pattern, $input, $matches);
if (isset($matches[1]))
foreach ($matches[1] as $key => $value)
{
$input = str_replace("$".$value, $replacements[$value], $input);
}
echo $input;
輸出:
這只小狗可笑。 不過,1300美元對於一只小狗來說是一筆不小的數目。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.