【问题标题】:Is there a function to add text to x if x not containing y | PHP如果 x 不包含 y | 是否有向 x 添加文本的功能? PHP
【发布时间】:2020-05-20 23:59:19
【问题描述】:

所以我正在开发一个 url 爬虫,但我得到了很多没有域和 http 的路径。 如果路径中不包含域和http,我想创建一个函数来添加它。 这是我的代码

<?php
$source_url = 'http://www.google.com/';
$html = file_get_contents($source_url);
$dom = new DOMDocument;
@$dom->loadHTML($html);
$links = $dom->getElementsByTagName('a');


foreach ($links as $link) {
    $input_url = $link->getAttribute('href');
    echo $input_url . "<br>";
}



?>

如果没有任何方法我可以提取包含 http 的网址

【问题讨论】:

  • 你可以做一个这样的函数。
  • PHP 具有可能有所帮助的 parse_url 函数。您无法直接从 DOMDocument 中获取您要查找的内容。

标签: php function url web-crawler


【解决方案1】:

您可以使用regular expressions 来检查链接是绝对 URL 还是相对链接,即是否包含域。我所做的是检查链接是否以http://https:// 开头。如果不是,则将源域添加到链接的开头。

foreach ($links as $link) {
    $input_url = $link->getAttribute('href');

    if (!preg_match('/^https?:\/\//', $input_url)) {
        $input_url = $source_url . preg_replace('/^\//', '', $input_url);
    }

    echo $input_url . "<br>";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-25
    • 2016-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多