【问题标题】:Find following x occurrences after a string with PHP regex?在使用 PHP 正则表达式的字符串后查找以下 x 次出现?
【发布时间】:2012-04-24 14:08:28
【问题描述】:

我想 preg_match 跟随 p 标签的 name="groups" 的所有 div id。如何在 PHP 中编写此表达式? (html 格式不正确,所以我不能使用 XPath ...)

<p name="groups">
  <div id="55">fifty-five</div>
  <div id="65">sixty-five</div>
  <div id="75">seventy-five</div>
</p>

理想的输出应该是这样的:

  array
    55
    65
    75

  array
    fifty-five
    sixty-five
    seventy-five

【问题讨论】:

  • 请贴出使用 XPath 失败的代码。
  • The html is malformed so I can't use XPath - 你认为正则表达式会更好吗?再想想……
  • 你不能指点我一个像样的“匹配此之后的任何东西”资源吗?我知道正则表达式会起作用而不是 XPath - 这就是我将它包含在问题中的原因......
  • 顺便说一句,dom 扩展从汤 html 中恢复得很好。也可以先通过 html tidy 扩展运行 html。

标签: php regex


【解决方案1】:

虽然使用正则表达式解析 html 通常并不好,但使用它匹配某些部分的 html 来完成有限的工作就可以了。

这是正则表达式:

<p name="groups">(\s*<div id="([0-9]+)">([a-z\-]+)</div>)+\s*</p>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-25
    • 2012-11-17
    • 2012-12-01
    相关资源
    最近更新 更多