【问题标题】:Replace words only in specific tags (regex)?仅替换特定标签中的单词(正则表达式)?
【发布时间】:2014-02-26 01:45:26
【问题描述】:

举例:

我想将 HTML 字符串中的 iOS 字词替换为 iOS 7,但仅限于正文中,以 <p> 标记开头(不包括任何其他情况)。

我只想替换这个:

<p>Say hello to iOS that is contained in the body text</p>
<p>Say hello to iOS 7 that is contained in the body text</p>

但不想替换这些:

<p>Say hello to <a href="#" alt="iOS 7 in alt text">this link.</a>
<p>Say hello to <img src="iOS 7.jpg" /> this image.
// And so on...

是否可以使用正则表达式?

【问题讨论】:

  • 可能吗?也许。可取的? Probably not
  • @kingkero 打败了我
  • 哇!哇。男人所有人都是我失去了Ponīyoo̼oonθ停止AN *̶̶͑̾̾͑̾̾g͇̫͛͆̾ͫ̑͆l͖͉̗̩̳̟̍ͫͥͨe̠̅s͎a̧͈͖r̽̾̈͒͑enootrè̑ͧ̌aͨl̘̝̙ͤ̾̆za̡͊͠͝lgì是̘̝̙͇̹̺ͤ̾̆ɲ̴ȳ̳͇̹̺ɲ̴ȳ̳p̯͍̭o̚n̐y̡h̸̡̪̯ͨ͊̽̅̾ȩ̬̩̾͛ͪ̈͘p̯͍̭o̚n̐m̖͊̒ͪͩͬ̚̚͜ȇ̴̟̟͙̞ͩ͌͝s̨̥̫͎̭ͯ̿̔****** span>
  • 我用正则表达式解析 HTML 一次...一次。

标签: php html regex tags preg-replace


【解决方案1】:

当然,您可以使用一个正则表达式,它使用否定的lookbehind。

(?

这基本上说匹配,除了前面有“...”的那些......

...但是您真的应该考虑使用某种 html 解析器,例如 BeautifulSoup,它可以让这一切变得微不足道。

看这里:

RegEx match open tags except XHTML self-contained tags

【讨论】:

  • 谢谢。但是上面的建议... ...err,建议我对内容进行策划,以将替换词标记为:iOS 7: 或其他内容。
猜你喜欢
  • 2020-06-03
  • 2019-10-24
  • 2020-01-06
  • 2018-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-10
相关资源
最近更新 更多