我很难从这个网站中提取括号之间的整数。
来自网站的部分标记:
<span class="b-label b-link-number" data-num="(322206)">Music & Video</span>
<span class="b-label b-link-number" data-num="(954218)">Toys, Hobbies & Games</span>
<span class="b-label b-link-number" data-num="(502981)">Kids, Baby & Maternity</span>
如何提取括号之间的整数?
期望输出:
322206
954218
502981
我应该使用Regex吗,因为它们有相同的类名(但不能使用Regex,因为括号内还有其他不需要的元素,也来自源代码)。
通常,这将是我提取信息的方式:
<?php
//header('Content-Type: text/html; charset=utf-8');
$grep = new DoMDocument();
@$grep->loadHTMLFile("http://global.rakuten.com/en/search/?tl=&k=");
$finder = new DomXPath($grep);
$class = "b-list-item";
$nodes = $finder->query("//*[contains(@class, '$class')]");
foreach ($nodes as $node) {
$span = $node->childNodes;
$search = array(0,1,2,3,4,5,6,7,8,9,'(',')');
$categories = str_replace($search, '', $span->item(0)->nodeValue);
echo '<br>' . '<font color="green">' . $categories . ' ' . '</font>' ;
}
?>
但既然我想要的数据在标签中,我该如何提取它们?
添加到当前代码中,这很简单,只需将$class
更改为您想要的类,并使用->getAttribute()
来获得data-num
的:
$grep = new DoMDocument();
@$grep->loadHTMLFile("http://global.rakuten.com/en/search/?tl=&k=");
$finder = new DomXPath($grep);
$class = "b-link-number"; // change the span class
$nodes = $finder->query("//*[contains(@class, '$class')]"); // target those
$numbers = array();
foreach ($nodes as $node) { // for every found elemenet
$link_num = $node->getAttribute('data-num'); // get the attribute `data-num`
$link_num = str_replace(['(', ')'], '', $link_num); // simply remove those parenthesis
$numbers[] = $link_num; // push it inside the container
}
echo '<pre>';
print_r($numbers);
<span[^>)()]*'(('d+)')[^>]*>
试试这个。抓住捕获物。请参阅演示。
http://regex101.com/r/iM2wF9/10