使用php代码从字符串中查找url和链接文本


Find url and link text from string using php code

我想从一个段落中找到url和超文本

,

$content = "<a href="http://google.com" target="_blank">Google</a> The biggest
search engine is google .The lot of people are used google 
<a href="http://google.com" target="_blank">Google</a>The google video 
service is youtube. <a href="http://youtube.com/ncvh/">Youtube</a>.
Google also provide <a href="http:/gmail.com">Gmail</a>.";

输出如

Text        Url                         Count   
Google      htp://google.com             2
Youtube     htp://youtube.com/ncvh/      1
Gmail       htp://gmail.com              1

谁来帮帮我

preg_match("/<a'shref'='"(.*)'"/",$content,$matches);

$matches是一个数组,其中包含正则表达式中用于查找链接的所有匹配项。每个捕获组是$matches中的一个索引。

注意你的<a>标签没有关闭。如果它们是关闭的,您还可以从链接中提取文本:

preg_match("/<a'shref'='"(.*)'">(.*)<'/a>/",$content,$matches);

我使用的正则表达式不是防水的。它依赖于双引号的使用,并期望href是<a>标记中的最后一个属性。您可以在在线库中找到优化的正则表达式,例如http://regexlib.com

我创建了很多html解析器。最适合我的方式:

preg_match_all('_<a(.*?)>(.*?)</a_i', $html, &$matches);获取属性和锚文本

preg_match('_href['s]*=['s]*[''"](.*?)[''"]_', $attrs, &$href)得到href

解析href到正确的url:

$url = str_replace(array(" ", "'n", "'r", "'t"), '', $url);
$url_components = parse_url(trim($url));