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

时间:2012-11-17 03:04:57

标签: php regex

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

例如,我有:

$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专业人士?

3 个答案:

答案 0 :(得分:2)

您可以在此处使用简单的评估技巧:

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

array_shift只会从替换数组中获取第一个条目。

最好使用地图("hello" => "hi")。

答案 1 :(得分:1)

我可以使用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?"

答案 2 :(得分:1)

如果您要做的就是将这三个特定短语与另一组特定短语分开,那么您可以使用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);
相关问题