1

我有一段 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 解析器。

4

1 回答 1

4

忽略使用正则表达式解析 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)
)
于 2012-10-04T17:33:32.963 回答