繁体   English   中英

PHP用单个正则表达式模式替换所有实例

[英]PHP replace all instances with single regex pattern

我有一个正则表达式,我想以最有效的方式替换匹配数组中的每个匹配与相应的替换数组。

例如,我有:

$string = '~~hello~~ there, how ~~are~~ ~~you~~?';

$pattern = '/~~(.*?)~~/';

$replacements = array();
$replacements[0] = 'hi';
$replacements[1] = 'am';
$replacements[2] = 'i';

我想把$string变为:

hi there, how am i?

最初我希望它像下面这样简单:

$string = preg_replace($pattern, $replacements, $string);

但它似乎没有用。 所以第一个问题是:如果$replacements是一个数组,那么$string也必须是一个数组吗?

现在,我可以提出(看似)效率低下的方法,例如计算匹配数并使数组填充适当数量的相同正则数。 但这引出了我们的问题二:是否有更有效的方法? 你会怎么做,PHP专业人士?

你可以在这里使用一个简单的评估技巧:

print preg_replace('/~~(\w+)~~/e', 'array_shift($replacements)', $st);

array_shift将简单地从替换数组中获取第一个条目。

更好的是使用地图( "hello" => "hi" )。

我可能会使用preg_replace_callback

$string = '~~hello~~ there, how ~~are~~ ~~you~~?';

$pattern = '/~~(.*?)~~/'; 

var_dump(preg_replace_callback($pattern, 
    function($matches) { 
        static $replacements = array('hi', 'am', 'i'), $i = 0; 
        return $replacements[$i++ % count($replacements)]; 
    }, 
    $string));

输出:

string(19) "hi there, how am i?"

如果您要做的就是用另一组特定短语切换这三个特定短语,那么您可以使用str_replace因为它比preg_replace快得多。

$subject = "~~hello~~ there, how ~~are~~ ~~you~~?";
$matches = array('~~hello~~', '~~are~~', '~~you~~');
$replace = array('hi', 'am', 'i');

str_replace($matches, $replace, $subject);

暂无
暂无

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

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