我想解析外部网页,并使用PHP从内容中提取所有url和链接文本。
例如,$content="<a href="http://google.com" target="_blank"> google</a> is very good search engine <a href="http://gmail.com" target="_blank">Gmail </a> is provided by google.
输出:http//google.com google
http//gmail.com Gmail
建议非常感谢!
如果你想使用正则表达式提取url和文本,那么以下应该可以工作:
<'s*a's*href's*='"(?<url>.*)'">(?<text>.*)</a>
但是用RegEx
解析HTML
不是一个好主意,你可以用DOM
类代替。
编辑
$content = "< a href="http://google.com" target="_blank"> google</a> is very good search engine < a href="http://gmail.com" target="_blank">Gmail </a> is provided by google .";
$html = new DOMDocument();
$html->loadHTML($content);
$anchors = $html->getElementsByTagName('a');
foreach ($anchors as $anchor) {
echo $anchor->getAttribute('href') . "'t" . $anchor->nodeValue;
}
您可以使用此REGEX模式href="([a-zA-Z0-9://. ]+)"
$pattern = 'href="([a-zA-Z0-9://. ]+)"';
$content = file_get_contents(FILE NAME HERE);
preg_match($pattern, $content, $matches);
print_r($matches);
这将列出所有链接。然后你可以解析它们