doufen3563 2011-10-25 15:33
浏览 37
已采纳

php正则表达式匹配html标签之外

I am making a preg_replace on html page. My pattern is aimed to add surrounding tag to some words in html. However, sometimes my regular expression modifies html tags. For example, when I try to replace this text:

<a href="example.com" alt="yasar home page">yasar</a>

So that yasar reads <span class="selected-word">yasar</span> , my regular expression also replaces yasar in alt attribute of anchor tag. Current preg_replace() I am using looks like this:

preg_replace("/(asf|gfd|oyws)/", '<span class=something>${1}</span>',$target);

How can I make a regular expression, so that it doesn't match anything inside a html tag?

  • 写回答

4条回答 默认 最新

  • doushi3819244 2011-10-25 15:48
    关注

    You can use an assertion for that, as you just have to ensure that the searched words occur somewhen after an >, or before any <. The latter test is easier to accomplish as lookahead assertions can be variable length:

    /(asf|foo|barr)(?=[^>]*(<|$))/
    

    See also http://www.regular-expressions.info/lookaround.html for a nice explanation of that assertion syntax.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 寻找电脑攻防的导师,有问题请教一下。
  • ¥20 微信同是win11,我的电脑安装不了pageoffice,一直无法打开
  • ¥15 这个界面我通过postman请求不到,但是通过浏览器可以正常访问
  • ¥15 动态规划算法实现背包问题
  • ¥15 wpf程序使用过程中异常奔溃
  • ¥15 多目标优化算法在与其他算法数据对比结果判断
  • ¥15 CPTN和EAST,主干网络是VGG16,请问在ICDAR2015数据集上训练之后,CPTN和EAST模型的大小为多少
  • ¥15 按颜色进行点云分割-python
  • ¥15 Matlab如何实现汽车变道切入场景的批量仿真
  • ¥15 无刷电机要通过什么才能做各种动作