【问题标题】:Regexp match string without substring [duplicate]没有子字符串的正则表达式匹配字符串[重复]
【发布时间】:2015-04-15 15:48:21
【问题描述】:

我想从 html 中获取段落或 div,但如果它不包含表单。 例如:

<p><form>I don't want this text</form>and not this text</p>
<p>I want to take this text</p>

我有工作变体,没有表单过滤器。

/(?:<(?:p|div)[^>]*>)(.*)(?:<\/(?:p|div)>)/iu

并且不使用过滤器的变体

/(?:<(?:p|div)[^>]*>)((?:.(?!<form))*)(?:<\/(?:p|div)>)/iu

你能帮帮我吗?

【问题讨论】:

标签: php regex html-parsing


【解决方案1】:

警告:使用 Regexp 解析 HTML 一直都是,而且永远都是一个坏主意。

这是您的正则表达式的略微修改版本:

/(?:<(?:p|div)[^>]*>)(?!.*\<form\>)(.*)(?:<\/(?:p|div)>)/iu

我对其进行了改进,让您可以捕捉到任何包含单词“form”(而不是标签)的段落。试试这个测试:

<p><form>I don't want this text</form>and not this text</p>
<p>I want to take this text even if it contains the "form" word!</p>
<p>I want to take this text</p>

【讨论】:

  • 谢谢,我突然明白我看的是 html,但是 regexp 使用的是简码 :) 抱歉,我的注意力不集中。
  • @StetsenkoStas 如果这解决了您的问题,请点击答案左侧的复选标记接受它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-08
  • 2017-11-09
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
相关资源
最近更新 更多