preg_replace除一列外的preg_quote


preg_replace with preg_quote except one column

我正在尝试使用与preg_quote一起使用preg_replace做一些技巧。

我有一个 json 数据对象数组以及我想要的内容

替换除一个键的值之外的所有键值

下面是输入数组的基本结构:

$posts = [{"title":"Test owy post avela","subtitle":"test subtitle",   
           "slug":"test owy-post-laravela-4", "created_at":"2014-11-02"}, 
          {...} ] 

我需要替换除slug键值之外的所有tes<span>tes</span>

下面是生成$posts的代码

$posts = Post::where('title', 'LIKE', '%'.$s.'%')->orWhere('content', 'LIKE', '%'.$s.'%')->get()->toArray();
foreach($posts as &$elm){
     $elm = array_map(function($i) use($s){
          return preg_replace("/(" . preg_quote($s) . ")/is", "<span style='background: #92CF18;'>$1</span>", $i);
     }, $elm);
}
如果您

只想对"SLUG"以外的所有行应用更改,我认为这就是您想要的:

$posts = Post::where('title', 'LIKE', '%'.$s.'%')->orWhere('content', 'LIKE', '%'.$s.'%')->get()->toArray();
foreach($posts as &$elm) {
    foreach ($elm as $key => $value)    {
        if ($key != 'SLUG') $elm[$key] = preg_replace("/(" . preg_quote($s) . ")/is", "<span style='background: #92CF18;'>$1</span>", $value);
    }
}

@cragimc答案是完全正确的,但您可以使用T-Regx库:

Pattern::prepare(["(", [$s], ")/is"])
    ->replace("<span style='background: #92CF18;'>$1</span>")
    ->all()
    ->with($value);