查找頁面中所有鏈接的PHP代碼

en9 9年前發布 | 2K 次閱讀 PHP


function get_links($link) {
    $html = file_get_contents($link);
    $html = str_replace("\n", "", $html);
    $html = preg_replace('/<a/i', "\n<a", $html);
    $html = preg_replace('/<\/a>/', "</a>\n", $html);
    preg_match_all('/<a\s*.*>.*?<\/a>/', $html, $matches);
    return($matches);
}

在這個例子中,我們想用file_get_contents來取得一個網頁的內容。然后用str_replace("\n", "", $html)把所有的換行去掉。再用preg_replace('/<a/i', "\n<a", $html)和preg_replace('/<\/a>/', "</a>\n", $html)來把所有的<a href=".....">.....</a>模式另起一行。最后就用preg_match_all('/<a\s.>.?<\/a>/', $html, $matches)匹配鏈接模式。/<a\s.>.?<\/a>/就是匹配<a href=".....">.....</a>這種模式的正則表達式。那我們為什么要把<a href=".....">.....</a>鏈接另起一行呢??因為在/<a\s.>.?<\/a>/模式中,.是不能匹配換行的,所以就如<a>和</a>不在同一行就不能匹配了!!所以我們要這樣做!

 本文由用戶 en9 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!