【问题标题】:Preg_replace match on word boundery and not in linkPreg_replace 匹配单词边界而不是链接
【发布时间】:2013-11-11 14:29:30
【问题描述】:

我正在尝试编写一个正则表达式来匹配边界上的单词,因为文本在 html 中,我需要避免使用 <a>here more words</a> 中的单词。

我现在的正则表达式是:/\bword\b/u

示例文本:

<p>Example lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur <a href="">porta lorem nec</a> tortor laoreet gravida.</p>

搜索单词lorem 应该只替换在开头,而不是&lt;a&gt;

【问题讨论】:

  • 请澄清您的问题并举例说明。

标签: php regex preg-replace


【解决方案1】:

你可以使用一些黑暗力量,如下所示:

&lt;a[^&gt;]*&gt;.*?&lt;/a\s*&gt;(*SKIP)(*FAIL)|\blorem\b

让我们分解一下:

<a[^>]*>            # match an opening "a" tag
.*?                 # match anything ungreedy until ...
</a\s*>             # match a closing "a" tag
(*SKIP)(*FAIL)      # skip it
|                   # or
\blorem\b           # match lorem with boundaries

所以基本上我们首先跳过所有a标签,然后我们匹配lorem

See a working demo

【讨论】:

【解决方案2】:

/u 在您的正则表达式中可能不合适或不需要。它通常在 PHP 中表示 unicode,但例如在 JavaScript 中不允许。
或者可能是您在 PHP 中使用 preg_match 而不是 preg_match_all

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-06
    相关资源
    最近更新 更多