正则表达式在HTML中获取值=“

时间:2013-08-28 20:50:18

标签: php

我想使用cURL从以下HTML代码中获取值 updateXXXX

<input type="hidden" id="_postupdate" name="_postupdate" value="updateXXXX" /><input type="hidden"(...)

我试过

$regex = '/name="_postupdate" value="(.*?)" \/><input type="hidden"/s';
if ( preg_match($regex, $page, $list) )
echo $list[0];

但没有成功。 有什么建议? :) 感谢

2 个答案:

答案 0 :(得分:4)

请勿使用regexp来解析HTML!而是让HTML解析器库为您担心标记的结构。

您可能希望使用DOMDocument类来执行此操作。然后,您可以使用XPath查询来提取数据。

您可以使用以下内容:

$html = '<input type="hidden" id="_postupdate" name="_postupdate" value="updateXXXX" />';


$dom = new DOMDocument();
$dom->loadHTML($html);

$xpath = new DOMXPath($dom);

$tags = $xpath->query('//input[@name="_postupdate"]');
foreach ($tags as $tag) {
    var_dump(trim($tag->getAttribute('value')));
}

答案 1 :(得分:0)

你要么像这样使用ungreedy开关:

$regex = '/name="_postupdate" value="(.*)" \/><input type="hidden"/Us';

或者你排除这样的引号:

$regex = '/name="_postupdate" value="([^"]*)" \/><input type="hidden"/s';

我同意在一般情况下不建议使用正则表达式来解析html。在这种情况下,要匹配的文本定义明确且简单。

正则表达式比html解析器更快,但如果html代码发生微小变化,它们将失败。在使用正则表达式时必须意识到这个弱点,如果代码可能随着时间的推移而发展,则必须避免使用正则表达式。