【问题标题】:preg_replace with preg_quote except one columnpreg_replace 用 preg_quote 除了一列
【发布时间】:2014-12-03 17:01:39
【问题描述】:

我正在尝试将preg_replacepreg_quote 一起使用。

我有一个 json 数据对象数组和我想要的

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

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

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

我需要将tes 的所有值替换为<span>tes</span>,除了slug 键的值

下面是生成$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);
}

【问题讨论】:

  • 您需要发布preg_quote返回的正则表达式

标签: php regex preg-replace preg-quote


【解决方案1】:

如果您只想对“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);
    }
}

【讨论】:

  • 这正是我想要的。谢谢!
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-21
    • 1970-01-01
    • 2013-01-10
    • 1970-01-01
    • 2014-05-25
    • 1970-01-01
    相关资源
    最近更新 更多