【问题标题】:Using preg_match to capture text between tags with exception with PHP [duplicate]使用 preg_match 捕获带有 PHP 异常的标签之间的文本 [重复]
【发布时间】:2019-06-15 23:20:49
【问题描述】:

file_get_contents 我得到一个 url 的 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>

在这种情况下,上面的代码不起作用。

你知道为什么吗?

谢谢。

【问题讨论】:

  • 你应该包括你在“工作”和“不工作”时得到的结果。只是为了清楚。

标签: php html preg-match preg-match-all


【解决方案1】:

这有点复杂,我们只需定义两个表达式并使用逻辑 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>([^<]+)?<

Demo

测试

$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

【讨论】:

  • 您好艾玛,非常感谢您的帮助。实际上,对于我页面的所有 HTML 代码,我有太多的匹配项。有没有办法我们可以更具体地整合Ville : ?提前非常感谢。
  • Emma,你知道为什么我现在用 PHP 出现这个错误:sandbox.onlinephpfunctions.com/code/…?谢谢。
  • 你好,Emma,当城市没有&lt;a&gt; 时,第二个效果很好。但如果它有&lt;a&gt; 则不起作用。你知道为什么吗?
  • 非常感谢艾玛。你今晚很有用。非常感谢。
【解决方案2】:

在这种情况下,另一种选择是使用DOMDocument,例如使用DOMXpath。然后从每个DOMElement 获取textcontentnodeValue

$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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多