0

您好,我的正则表达式代码有问题,我使用 PHP 从 HTML 标记中获取值。我有以下可能的字符串:

<span class="down last_position">xyz</span>
<span class="up last_position">xyz</span>
<span class="last_position new">xyz</span>

我有以下 preg_match 命令:

preg_match('#<span class="last_position.*?">(.+)</span>#', $string, $matches);

这几乎涵盖了案例#3。所以我想知道我需要在 last_position 前面添加什么来获得所有可能的情况..?

非常感谢..

编辑:对于所有想知道要匹配什么值的人:“xyz”

4

5 回答 5

5

避免使用正则表达式来解析 HTML,因为它容易出错。使用 DOM 解析器可以更好地解决您的特定用例:

$html = <<< EOF
<span class="down last_position">xyz</span>
<span class="up last_position">xyz</span>
<span class="last_position new">xyz</span>
EOF;
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($html); // loads your html
$xpath = new DOMXPath($doc);
$nodeList = $xpath->query("//span[contains(@class, 'last_position')]/text()");
for($i=0; $i < $nodeList->length; $i++) {
    $node = $nodeList->item($i);
    var_dump($node->nodeValue);
}

输出:

string(3) "xyz"
string(3) "xyz"
string(3) "xyz"
于 2013-04-26T07:54:19.590 回答
1

尝试使用这个

preg_match('#<span class="?(.*)last_position.*?">(.+)</span>#', $string, $matches);
于 2013-04-26T07:54:45.870 回答
1

你可以试试这个:

preg_match_all('#<span class="[^"]*last_position[^"]*">(.+)</span>#', $string, $matches, PREG_PATTERN_ORDER);

然后,您将在$matches[1][0], $matches[1][1], $matches[1][2]...中找到值。

我在类属性值中添加的部分[^"]*匹配任意数量的不匹配双引号的字符。因此它匹配属性值内的任何内容。

于 2013-04-26T07:55:13.523 回答
1

尝试以下操作(是的,您可以使用正则表达式来匹配来自 HTML 的数据):

$string = '<span class="down last_position">xyz</span>
<span class="up last_position">xyz</span>
<span class="last_position new">xyz</span>';

preg_match_all('#<span\s.*?class=".*?last_position.*?".*?>(.+?)</span>#i', $string, $m);
print_r($m);

在线演示

于 2013-04-26T07:55:44.303 回答
0

当然,使用 RegEx 解析XML是不可能的,因为 XML 不规则。但在许多实际情况下,用作输入的 XML 文档是有限且可预测的,足以被简单地视为文本。

像这样的东西应该适合你:

preg_match('#<span class="[^>"]*?last_position[^>"]*">(.+)</span>#', $string, $matches);
于 2013-04-26T08:00:23.417 回答