本文分享的这段代码,使用php正则从超链接中提取文本。
例如,可以从<a href= http://www.jb200.com >Link</a>中,获取文本内容:Link。
代码如下:
<?php
/**
* @从超链接中提取文本
* @param string $url
* @return string
* @edit www.jb200.com
*/
function getUrlLinkText($url)
{
/*** find the link test ***/
preg_match('/>(.*)</a>/', $url, $matches);
/*** return the match ***/
return $matches[1];
}
/*** example usage ***/
$url = '<a href="http://www.jb200.com" class="something" id="link_id">Url Text Link Here</a>';
echo getUrlLinkText($url);
?>
再一次感受到php正则的强大,有兴趣的朋友,还可以在这上面进行扩展,以实现更强大的功能,比如提取链接、提取图片链接、提取图片链接中的文本等。