【问题标题】:How to convert a .Net regular expression to php如何将.Net正则表达式转换为php
【发布时间】:2013-10-07 13:36:41
【问题描述】:

如果短语不包含在 HTML 锚标记或 IMG 标记中,我有一个用于替换短语的正则表达式。在本例中,要搜索的短语是“hello world”

.net 正则表达式是

(?<!<a [^<]+)(?<!<img [^<]+)(?<=[ ,.;!]+)hello world(?=[ ,.;&!]+)(?!!.*</a>)

例如正则表达式应匹配短语中的“hello world”,如

"one two three hello world four five"

但不应匹配 hello world 之类的短语

"one two three <a href='index.html'> hello world </a> four five"

"one two three <img alt='hello world' \>four five"

它与我最初开发 .Net 版本时的以下问题有关。 regular expression that doesn't match a string if it's the text within an html anchor tag

非常感谢任何有关如何将其转换为 php 正则表达式的指导。

【问题讨论】:

  • 这个正则表达式也不应该匹配 .NET 中的任何内容。结束标记有一个斜杠 (&lt;/a&gt;),但您的表达式会查找反斜杠。
  • @DanielHilgarth 感谢您的更正,我已经更新了问题。
  • 现在有什么问题?
  • 它不是在寻找图像标签的结束“>”吗?
  • 这与 .NET 与 PHP 有什么关系?您的正则表达式根本不包含会寻找类似内容的部分......

标签: php .net regex


【解决方案1】:

注意:请勿使用正则表达式解析标签。

对于aimg 标签,您可以执行以下操作。

(?!<(?:a|img)[^>]*?>)\bhello world\b(?![^<]*?(?:</a>|>))

live demo

我想对于标签内或标签之间的任何东西,你都可以试试这个。

(?!<[^>]*?>)\bhello world\b(?![^<]*?(?:</[^/]*>|>))

live demo

【讨论】:

  • 我已经成功地使用了您的第一个正则表达式,并对不区分大小写的匹配进行了微调。感谢您的帮助和现场演示,下次我不幸不得不编写正则表达式时,我将使用该网站。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-02
  • 2013-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多