使用简单的HTML dom解析,将结果放入数组中,然后仅获取我想要的结果



我很确定我的标题可能会让你感到困惑,但我有一个问题。 简单地说,我正在解析$url中的所有标题名称,然后打印它们......它工作得很好问题:但是如果我不想向我显示第一个标题名称和第三个标题名称怎么办?是否可以将代码正确到foreach并说例如don't get the first[0] and the third[2]但采用所有其他标题名称。如果是或回答了这个问题,请重定向我,因为我找不到一些东西。

这是我下面的代码。

include 'lib/simple_html_dom.php';
$url="http://hallofbeorn.com/LotR?CardSet=The+Hunt+for+Gollum";
$html=file_get_html($url);
$array = [];
foreach ($html->find('a[style="margin-bottom:2px;font-size:medium;font-weight:bold;display:inline- 
block;"]') as $values) {
$array[] = $values->plaintext;
}
print_r($array);

我知道我可以用这种方式做到这一点:print_r($array[1]);print_r($array[3]);print_r($array[4]);......等等,但我问foreach内是否有更快的方法

你应该看看正则表达式。
试试这个:

$url="http://hallofbeorn.com/LotR?CardSet=The+Hunt+for+Gollum";
$html=file_get_contents($url);
$pattern = '/<a href="(.*)" style="margin-bottom:2px;font-size:medium;font-weight:bold;display:inline-block;">(.*)</a>/m';
preg_match_all($pattern, $html, $matches);
print_r($matches[2]);

一个简单的if语句可以帮助您:

foreach ($html->find('a[style="margin-bottom:2px;font-size:medium;font-weight:bold;display:inline-block;"]') as $i => $values) {
if($i != 0 && $i != 2) {
$array[] = $values->plaintext;
}
}
print_r($array);

您可以使用正则表达式来获取数据。

$url="http://hallofbeorn.com/LotR?CardSet=The+Hunt+for+Gollum";
$html=file_get_contents($url);
$pattern = '/(?P<cards><a href=".*" style="margin-bottom:2px;font-size:medium;font-weight:bold;display:inline-block;">.*</a>)/';
preg_match_all($pattern, $html, $matches);
header('content-type: text/plain; charset=utf-8');
print_r($matches);

最新更新