用preg_quote代替preg_replace,但只有一列 [英] preg_replace with preg_quote except one column
本文介绍了用preg_quote代替preg_replace,但只有一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 preg_replace
的一些技巧与 preg_quote 一起使用.
I'm trying to make some tricks with preg_replace
used with preg_quote.
我有一个json数据对象数组以及我想要的内容
I have an array of json data object and what I want to
替换除一个键的值之外的所有键的值
Replace all values of keys except the value of one key
下面是输入数组的基本结构:
Below is the basic structure of the input array:
$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
键的值
and I need to replace all values of tes
to <span>tes</span>
except from slug
key's value
下面是生成$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"以外的所有行,我想这就是您想要的:
If you just want to apply the change for all rows other than "SLUG", I think this is what you want:
$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);
}
}
这篇关于用preg_quote代替preg_replace,但只有一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文