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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀