【问题标题】:Regex PCRE expression正则表达式 PCRE 表达式
【发布时间】:2012-10-04 17:13:00
【问题描述】:

我有一段 html 代码,如下所示:

<td width="24%"><b>Something</b></td>
          <td width="1%"></td>
          <td width="46%" align="center">
           <p><b>
    needed
  value</b></p>
          </td>
          <td width="28%" align="center">
            &nbsp;</td>
        </tr>

提取单词Something之后的第一个文本节点(不是标签,而是里面的文本)的一个好的正则表达式模式是什么我的意思是我想提取

     needed
  value

仅此而已。

我无法在 php 中找出有效的正则表达式模式。

编辑: 我不是在解析整个 html 文档,而是其中的几行,所以我只想使用 Regex 而不是 HTML 解析器来完成它。

【问题讨论】:

标签: php regex pcre


【解决方案1】:

忽略使用正则表达式解析 HTML 的潜在问题,以下模式应与您的示例代码匹配:

Something(?:(?:<[^>]+>)|\s)*([\w\s*]+)

这将匹配 Something,后跟任何 HTML 标记(或空格)列表,并匹配下一个文本块 \w(包括空格)。

您可以在 PHP 的 preg_match() 方法中使用它,如下所示:

if (preg_match('/Something(?:(?:<[^>]+>)|\s)*([\w\s*]+)/', $inputString, $match)) {
    $matchedValue = $match[1];
    // do whatever you need
}

正则表达式解释:

Something         # has to start with 'Something'
(?:               # non-matching group
    (?:           # non-matching group
        <[^>]+>   # any HTML tags, <...>
    )
    | \s          # OR whitespace
)*                # this group can match 0+ times
(
    [\w\s*]+      # any non-HTML words (with/without whitespace)
)

【讨论】:

  • 谢谢!这就是我所需要的。我觉得这个解释也很有用。
猜你喜欢
  • 1970-01-01
  • 2023-03-20
  • 2014-08-02
  • 1970-01-01
  • 2014-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多