从file_get_contents
中,我获得了网址的HTML代码。
$html = file_get_contents($url);
现在,我想捕获<span class="place ville">Ville : <span>
和</span>
之间的城市名称。
HTML代码是:
<span class="place ville">Ville : <span>City name</span></span>
所以我正在用这个:
preg_match('/<span class=\"place ville\">Ville : <span>(.+?)<\/span>/is', $html, $city);
$arr['city'] = $city[1];
有效。
但是有时,下面的代码带有链接:
<span class="place ville">Ville : <span><a href="https://example.com">City name</a></span></span>
在这种情况下,上面的代码不起作用。
你知道为什么吗?
谢谢。
答案 0 :(得分:3)
这有点复杂,我们只需要定义两个表达式并使用逻辑OR |
将它们连接起来:
<span class="place ville">Ville : <span><.+?>(.+?)<\/
和
<span class="place ville">Ville : <span>([^<]+)?<
<span class="place ville">Ville : <span><.+?>(.+?)<\/|<span class="place ville">Ville : <span>([^<]+)?<
$re = '/<span class="place ville">Ville : <span><.+?>(.+?)<\/|<span class="place ville">Ville : <span>([^<]+)?</m';
$str = '<span class="place ville">Ville : <span>City name</span></span>
<span class="place ville">Ville : <span><a href="https://example.com">City name</a></span></span>
<span class="place ville">Ville : <span>Århus</span></span>
<span class="place ville">Ville : <span><a href="https://example.com">City name</a></span></span>
';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
foreach ($matches as $key => $city) {
if ($city[1] == "") {
echo $city[2] . "\n";
} else {
echo $city[1] . "\n";
}
}
City name
City name
Århus
City name
答案 1 :(得分:1)
在这种情况下,另一种选择是使用DOMDocument,例如使用DOMXpath。然后从每个DOMElement中获得textcontent或nodeValue:
$html = <<<HTML
<span class="place ville">Ville : <span>City name 1</span></span>
<span class="place ville">Ville : <span><a href="https://example.com">City name 2</a></span></span>
HTML;
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXpath($dom);
$nodeList = $xpath->query("//span[contains(@class, 'place') and contains(@class, 'ville')]/span");
foreach ($nodeList as $n) {
echo $n->textContent . PHP_EOL;
}
结果
City name 1
City name 2
查看Php demo