使用SimpleHTMLDomParser和正则表达式查找所有外部链接


Find all external links with Simple HTML Dom Parser and regular expressions?

如何使用正则表达式和Simple HTML DOM Parser查找页面上的所有外部链接?我有以下代码来查找所有链接。

<?php
    include_once('simple_html_dom.php');
    $url = "http://www.tokyobit.com";
    $html = new simple_html_dom();
    $html->load_file($url);
    foreach($html->find('a') as $a){
        echo $a;
    }
?>

如何添加正则表达式来查找以http://https://ftp://开头的所有链接?

foreach($html->find('a') as $a){
    $regex = ; //regex here
    if(preg_match_all($regex, $a, $matches)){
        foreach($matches as $match){
            echo $match . '<br />';
        }
    }
}

将$regex变量更改为:

$regex = "#(https?|ftp)://.#";

您可以使用自定义strpos将数组用作指针

你首先需要这个功能

function strposa($haystack, $needle, $offset=0) {
    if(!is_array($needle)) $needle = array($needle);
    foreach($needle as $query) {
        if(strpos($haystack, $query, $offset) !== false) return true; // stop on first    true result
    }
    return false;
}

然后在你的代码

$needle = array("ftp://","http://","https://");
foreach($html->find('a') as $a){
    if(strposa($a, $needle){
        echo $matches;
    }
}

试试这个:

foreach($html->find('a') as $a){
    if(preg_match('#^(?:https?|ftp)://.+$#', $a->href)){
        echo $matches;
    }
}

你可以这样做:

include_once('simple_html_dom.php');
$url = "http://www.tokyobit.com";
$html = new simple_html_dom();
$html->load_file($url);
$result = array();
foreach($html->find('a') as $a){
    $href = $a->href;
    if (strpos($href, '://', 3)!==false) $result[] = $href;
}
print_r($result);