我想知道是否有一种简单的方法可以使用
preg_replace
中的匹配模式作为替换值数组的索引。
例如
preg_replace("/\{[a-z_]*\}/i", "{$data_array[\1]}", $string);
搜索像
{xxx}
这样的占位符,并将其替换为 $data_array['xxx']
中的值,其中 xxx
是大括号内的匹配文本。
但是这个表达式不起作用,因为它是无效的 php。
我写了以下函数,但我想知道是否可以简单地做到这一点。我可以使用回调,但我如何将
$data_array
传递给它?
function mailmerge($string, $data_array, $tags='{}')
{
$tag_start=$tags[0];
$tag_end =$tags[1];
if( (!stristr($string, $tag_start)) && (!stristr($string, $tag_end)) ) return $string;
while(list($key,$value)=each($data_array))
{
$patterns[$key]="/".preg_quote($tag_start.$key.$tag_end)."/";
}
ksort($patterns);
ksort($data_array);
return preg_replace($patterns, $data_array, $string);
}
我的脑海里:
preg_replace_callback("/\{([a-z_]*)\}/i", function($m) use($data_array){
return $data_array[$m[1]];
}, $string);
注意:以上功能需要PHP 5.3+。
关联数组替换 - 如果未找到则保留匹配的片段:
$words=array("_saudation_"=>"Hello", "_animal_"=>"cat", "_animal_sound_"=>"MEooow");
$source=" _saudation_! My Animal is a _animal_ and it says _animal_sound_ , _no_match_";
echo (preg_replace_callback("/\b_(\w*)_\b/", function($match) use ($words) { if(isset($words[$match[0]])){
return ($words[$match[0]]);}else{
return($match[0]);}
}, $source));
//returns: Hello! My Animal is a cat and it says MEooow , _no_match_
*注意,虽然“_no_match_”缺少翻译,但它会在正则表达式中匹配,但是 保留其密钥。
从 PHP7.4 开始,箭头语法是此
preg_replace_callback()
任务最简洁的语法。匹配两个大括号之间的零长度子字符串没有意义,因此我将使用 +
作为一个或多个量词。
如果在查找数组中未找到匹配的子字符串作为键,请重新插入完整的字符串匹配,以使占位符显示不变。
代码:(演示)
$string = 'try replacing {foo} and {huh} and {bar} in text';
$data_array = [
'foo' => 'fighters',
'bar' => 'snacks',
];
echo preg_replace_callback(
'/{(\w+)}/',
fn($m) => $data_array[$m[1]] ?? $m[0],
$string
);
输出:
try replacing fighters and {huh} and snacks in text