我需要从下面的html代码中获取php中的h2和h3标记为$var:
<div class="main-info">
<img class="iphone-img" alt="" src="https://www.myweb.com/securedImage.jsp">
<div class="sub-info">
<h2 class="model">iPhone 4S</h2>
<h3 class="capacity color">16GB Black</h3>
</div>
</div>我想要这个结果:
echo $model; // Should echo: 'iPhone 4S'
echo $capacitycolour; // Should echo: '16GB Black'我试过preg_match,preg_match_all和getElementsByTagName,但是到目前为止没有运气。
下面是我尝试过的代码:
$pattern = '/[^\n]h2*[^\n]*/';
preg_match_all($pattern,$data, $matches, PREG_OFFSET_CAPTURE);
var_dump($matches);以及:
$doc = new DOMDocument();
$doc->loadHTML($data);
$tags = $doc->getElementsByTagName('sub-info');
$root = $doc->documentElement;
foreach($root->childNodes as $node){
$attributes[$node->nodeName] = $node->nodeValue;
}
var_dump($attributes);发布于 2015-12-17 08:46:04
sub-info是类,而不是标签名,因此您对DOMDocument的使用是有缺陷的,您可能最好使用XPath查询。
$strhtml='<div class="main-info">
<img class="iphone-img" alt="" src="https://www.myweb.com/securedImage.jsp?configcode=DTF9&size=120x120">
<div class="sub-info">
<h2 class="model">
iPhone 4S
</h2>
<h3 class="capacity color">
16GB Black
</h3>
</div>
</div>';
$doc = new DOMDocument();
$doc->loadHTML( $strhtml );
$xpath=new DOMXPath( $doc );
$col=$xpath->query('//div[@class="sub-info"]/h2|//div[@class="sub-info"]/h3');
if( $col ){
/* You could store results from query in an array */
$tags=array();
foreach( $col as $node ) {
/* Simplest form to display results on separate lines, use br tag */
echo $node->nodeValue . '<br />';
/* Add tags to array - a rethink would be required if there are multiple h2 and h3 tags! */
$tags[ $node->tagName ]=$node->nodeValue;
}
/* echo back results from array */
echo $tags['h2'];
echo '<br />';
echo $tags['h3'];
}发布于 2015-12-17 08:48:36
将来,只需尝试在线regex测试器来验证您的表达式。
对于H2-标记,以下内容可以工作:.*<h2.*>[\n\s]*(.*) (尽管没有找到最理想的)
发布于 2015-12-17 08:45:25
我以前在很多情况下都使用过dom.php,并且工作得很好。它允许在加载文档后使用类似选择器的CSS。此外,您还可以解析字符串、本地文件或URL!下面将为您提供一个Element的数组:
$div = $html->find('div.sub-info');
$ret = $div[0]->find('h2, h3');API参考:这里
警告:不要使用RegEx解析这里,如果您确实看到了会发生什么:)
https://stackoverflow.com/questions/34330056
复制相似问题