Php 从字符串中提取超链接的函数

Php function to extract hyperlink from string

我需要从 html 字符串中提取 link 的函数。 示例:

字符串:

<!-- BEGIN PARTNER PROGRAM - DO NOT CHANGE THE PARAMETERS OF THE HYPERLINK -
-> <a href='http://www.link.com' target='_blank'>text</a> <img 
src='http://www.linkimage.com' BORDER='0' WIDTH='1' HEIGHT='1' /> <!-- END 
PARTNER PROGRAM --> 

需要提取:

http://www.link.com

感谢

$string = "<!-- BEGIN PARTNER PROGRAM - DO NOT CHANGE THE PARAMETERS OF THE HYPERLINK -
-> <a href='http://www.link.com' target='_blank'>text</a> <img 
src='http://www.linkimage.com' BORDER='0' WIDTH='1' HEIGHT='1' /> <!-- END 
PARTNER PROGRAM --> ";

    $link = explode('<a href=\'', $string)[1];
    $link = explode('\'',$link)[0];
    echo $link;

    $linkimage = explode('src=\'', $string)[1];
    $linkimage = explode('\'',$linkimage)[0];
    echo $linkimage;

快速 n 肮脏的方法:

preg_match_all('~href=([\'"])([^\'"]+)\1~is', $htmlString, $matches); 

print_r($matches[2]);

正确的方法:

http://php.net/manual/en/domdocument.getelementsbytagname.php / http://php.net/manual/en/simplexmlelement.xpath.php 等等..

正确方法的问题是您需要在解析前整理 html。在某些情况下,甚至 php 本机 http://php.net/manual/en/book.tidy.php 也无法正确做到这一点。