php – 从数组中替换(添加)区分大小写的单词
发布时间:2020-12-13 17:01:39 所属栏目:PHP教程 来源:网络整理
导读:我是php的新手,尤其是正则表达式. 我的目标是使用数组中列出的“关键字”提示自动丰富文本. 到目前为止我来了. $pattern = array("/bexplanationsb/i","/btargetb/i","/bhintsb/i","/bhintb/i",);$replacement = array("explanations i(Erkl?rungen)
我是php的新手,尤其是正则表达式.
我的目标是使用数组中列出的“关键字”提示自动丰富文本. 到目前为止我来了. $pattern = array("/bexplanationsb/i","/btargetb/i","/bhintsb/i","/bhintb/i",); $replacement = array("explanations <i>(Erkl?rungen)</i>","target <i>Ziel</i>","hints <i>Hinsweise</i>","hint <i>Hinweis</i>",); $string = "Target is to add some explanations (hints) from an array to this text. I am thankful for every hint."; echo preg_replace($pattern,$replacement,$string); 收益: target <i>Ziel</i> is to add some explanations <i>(Erkl?rungen)</i> (hints <i>Hinsweise</i>) from an array to this text. I am thankful for every hint <i>Hinweis</i> 1)一般来说,我想知道是否有更优雅的解决方案(最终没有替换原始单词)? 2)我怎样才能实现“目标”一词对案例敏感的待遇? 对不起,我的英语和许多提前感谢. 解决方法
在正则表达式模式中用括号括起搜索词,并在替换中使用反向.
见PHP demo: $pattern = array("/b(explanations)b/i","/b(target)b/i","/b(hints)b/i","/b(hint)b/i",); $replacement = array('$1 <i>(Erkl?rungen)</i>','$1 <i>Ziel</i>','$1 <i>Hinsweise</i>','$1 <i>Hinweis</i>',); $string = "Target is to add some explanations (hints) from an array to this text. I am thankful for every hint."; echo preg_replace($pattern,$string); 这样,您将替换为文本中使用的实际案例中找到的单词. 请注意,确保模式按降序排列是非常重要的,较长的模式会出现在较短的模式之前(第一个目标,然后是目标等) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |