2014-12-03 76 views
0

我試圖做一些preg_replacepreg_quote一起使用的技巧。preg_replace與preg_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); 
} 
+0

你需要發佈'preg_quote'返回的正則表達式 – Machavity 2014-12-03 17:25:28

回答

1

如果你只是想申請變更爲比「彈頭」以外的所有行的代碼,我認爲這是你想要的東西:

$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); 
    } 
} 
+0

這正是我想要的。謝謝! – Zolax 2014-12-03 17:35:23