PHP preg_replace多个单词

时间:2016-06-14 13:32:34

标签: php

使用preg_replace替换字符串时遇到问题。

function addClass($search, $string) {

    return preg_replace("/\b($search)\b/", "<div class=mark>$1</div>", $string);

}

$string = "We won again"; 
$result  = addClass("We", $string);

output ---> <div class=mark>We</div> won again

我想为多个字符串设置$search

$string = "We won again"; 
$result  = addClass(array("We", "again"), $string);

output ---> <div class=mark>We</div> won <div class=mark>again</div>

如何创建多个搜索,将字符串放入数组?

提前致谢。

2 个答案:

答案 0 :(得分:2)

您可以在正则表达式中使用or表达式 - (We|again)

function addClass($search, $string) {
    return preg_replace("/\b(". implode('|', $search) . ")\b/", "<div class=mark>$1</div>", $string);
}

并且,如果要保存旧语法,请从单个字符串创建一个数组:

function addClass($search, $string) {
    if(! is_array($search)) $search = array($search);
    return preg_replace("/\b(". implode('|', $search) . ")\b/", "<div class=mark>$1</div>", $string);
}

demo

答案 1 :(得分:2)

使用is_arrayarray_map函数的替代解决方案:

function addClass($search, $string) {
    $search = (is_array($search))? array_map(function($v) { return "/\b($v)\b/"; }, $search) : ["/\b($search)\b/"];
    return preg_replace($search, "<div class=mark>$1</div>", $string);
}