dongtang4954 2013-07-03 05:18
浏览 29
已采纳

PHP:正则表达式使用Lookbehind Assertions中的通配符替换单词

I'm looking to create a PHP Regex script that can match and replace words within a string.

The regex needs to match only complete words, which I can easily accomplish with:

/\b(SEARCH_TERM)\b/

The problem I am having is that some of the strings contain html elements as such as <a> tags and <img> tags, where the href and src attributes may sometimes contain the to-be-replaced word within their path. If this word is replaced within these elements, then the link or image will no longer work.

Example, replace the word 'test' with 'SEARCH_TERM' for the following example string:

my test string <a href="http://www.google.com?q=my+test+string">link</a>

Would return:

my SEARCH_TERM string <a href="http://www.google.com?q=my+SEARCH_TERM+string">link</a>

Whereas I need it to ignore the href attribute text and return:

my SEARCH_TERM string <a href="http://www.google.com?q=my+test+string">link</a>

I've looked at using Regex's Lookbehind Assertions (As just below), but variable length wildcard characters are not allowed.

/(?<!(href|src)=.*)\b(SEARCH_TERM)\b/

Note: I specifically need to do this with Regex, and not a DOM parser.

  • 写回答

1条回答 默认 最新

  • dongmuyuan3046 2013-07-03 05:28
    关注

    As I mentioned you need to use an html parser.

    But if you want it

    /\btest\b(?=[^>]*(<|$))/s
    

    Above regex would match only if there's < or end of string(not line) ahead somewhere without matching >


    NOTE

    This would not work if your text itself contains >.

    For example

     hello>world
    

    Hence the reason you should use a parser

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大