【问题标题】:php preg_replace how to exclude casephp preg_replace 如何排除大小写
【发布时间】:2020-07-07 16:51:51
【问题描述】:

我有以下preg_replace

foreach ($financeTermsArray as $term => $info) {

   $content = preg_replace($term, $info, $content, 1);
}

$info 变量的样子

'<a class="glossar-word" href="' . get_permalink() . '" data-glossar="' . $excerpt . '">' . get_the_title() . '</a>';

$term 变量如"/\b" . get_the_title() . "\b/"

如果匹配的单词在data-glossar html 属性中,我想从preg_replace 中排除。

我该怎么做?

我得到了它使用以下模式:

"/data-glossar=\"([^\"]*)(*SKIP)(*F)|\b" . get_the_title() . "\b/"

【问题讨论】:

  • 正则表达式在哪里?
  • matched word 等于从get_the_title() 返回的内容因此,您必须将get_the_title() 返回的内容合并到一个正则表达式中,该正则表达式跳过包含data-glossar 属性中的该值的标签.那是你要的吗 ?还是您需要先排除所有标签?
  • 是的,因为$content 正在更新循环匹配,并且数据属性值可能包含关键字,在这种情况下应该跳过。
  • I want to exclude from preg_replace if matched word is inside data-glossar html attribute.I got it working with the following pattern: 实际上该模式在技术上与该属性不匹配,因为它不是标签/属性正则表达式。我的正则表达式排除了所有 html,因此它永远不会失败,也永远不会有歧义。如果我给了你SKIP/FAIL的想法,你能接受并支持我的回答吗?
  • 顺便说一句,为了安全起见,"\b/" 应该是 "\\b/"

标签: php regex preg-replace


【解决方案1】:

这是一个在运行时使用get_the_title() 构造的正则表达式。
构造正则表达式时,会SKIP ALL TAGS在html中,包括
不可见的内容,并且只会匹配'\b' . get_the_title() . '\b'
如发现 OUTSIDE 标签。

无论如何我都不需要测试生成的正则表达式字符串,所以你应该这样做
先看看好不好。

按原意在 preg_replace 上使用它。

$term = '~<(?:(?:(?:(script|style|object|embed|applet|noframes|noscript|noembed)(?:\s+(?>"[\S\s]*?"|\'[\S\s]*?\'|(?:(?!/>)[^>])?)+)?\s*>)[\S\s]*?</\1\s*(?=>))|(?:/?[\w:]+\s*/?)|(?:[\w:]+\s+(?:"[\S\s]*?"|\'[\S\s]*?\'|[^>]?)+\s*/?)|\?[\S\s]*?\?|(?:!(?:(?:DOCTYPE[\S\s]*?)|(?:\[CDATA\[[\S\s]*?\]\])|(?:--[\S\s]*?--)|(?:ATTLIST[\S\s]*?)|(?:ENTITY[\S\s]*?)|(?:ELEMENT[\S\s]*?))))>(*SKIP)(*FAIL)|'
        . '\b' . get_the_title() . '\b~';

【讨论】:

    猜你喜欢
    • 2014-08-29
    • 2019-04-23
    • 2013-10-19
    • 1970-01-01
    • 1970-01-01
    • 2018-11-14
    • 1970-01-01
    • 2012-12-04
    • 2016-12-24
    相关资源
    最近更新 更多