Php 使用模式作为替换数据数组索引的preg_replace
我想知道是否有一种简单的方法可以使用Php 使用模式作为替换数据数组索引的preg_replace,php,regex,preg-replace,Php,Regex,Preg Replace,我想知道是否有一种简单的方法可以使用preg_replace中的匹配模式作为替换值数组的索引 e、 g 搜索{xxx}并将其替换为$data_数组['xxx']中的值,其中xxx是一个模式 但是这个表达式不能像它的无效php那样工作 我已经编写了下面的函数,但是我想知道是否可以简单地实现它。我可以使用回调,但是如何将$data\u数组也传递给它呢 function mailmerge($string, $data_array, $tags='{}') { $tag_start=$tags
preg_replace
中的匹配模式作为替换值数组的索引
e、 g
搜索{xxx}并将其替换为$data_数组['xxx']中的值,其中xxx是一个模式
但是这个表达式不能像它的无效php那样工作
我已经编写了下面的函数,但是我想知道是否可以简单地实现它。我可以使用回调,但是如何将$data\u数组也传递给它呢
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);
}
您可以使用并编写一个可以使用该数组索引的函数,或者可以使用e
修饰符来计算替换字符串(不过请注意,e
修饰符已被弃用,因此回调函数是更好的解决方案) 从我的脑海中:
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_
*请注意,尽管“\u no\u match\u”缺少翻译,但它将在正则表达式中匹配,但是
保留其键。使用
preg\u replace\u callback()
在这种情况下(您已经过滤了输入数据),您可以使用/e
修饰符(您的卷曲字符串表达式仍然需要数组键引号)。然而,它现在是非法的,与p\u r\u回调相比,它的优势有限。请注意,您还需要一个捕获组/\{([a-z]*)\}/i
。干杯,哈姆扎。我知道preg_replace_callback(),只是不知道如何将其传递给数据数组。(在问题中)Cheers-必须稍微更改它\{([a-z]*)\}
和$data\u数组[$m[1]]
这是对@Hamza solution的改进,因为如果没有找到特定Matchey的索引,它将崩溃!很好的解决方案,我应该包括额外的检查以及+1.
$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_