从HTML解析数据时,您实际上不应该使用正则表达式。看一下DOMXPath
Query函数。
现在,实际代码可能是:
[编辑] Stefan Gehrig为XPath提供了更好的查询,因此代码可以简化为:
libxml_use_internal_errors(true); // Yeah if you are so worried about using @ with warnings$doc = new Domdocument();$doc->loadHTML($html);$xpath = new DOMXPath($doc);$query = '/meta';$metas = $xpath->query($query);$rmetas = array();foreach ($metas as $meta) { $property = $meta->getAttribute('property'); $content = $meta->getAttribute('content'); if(!empty($property) && preg_match('#^og:#', $property)) { $rmetas[$property] = $content; }}var_dump($rmetas);


