下面的方法使链接可点击。这是一个过滤器。您发送文本字符串,它将 http 和 https 转换为可点击的链接。
/**
* Make clickable links from URLs in text.
*
*/
public function make_clickable($text) {
return preg_replace_callback(
'#'b(?<![href|src]=[''"])https?://[^'s()<>]+(?:'(['w'd]+')|([^[:punct:]'s]|/))#',
create_function(
'$matches',
'return "<a href=''{$matches[0]}''>{$matches[0]}</a>";'
),$text);
}
我想扩展此方法以接受 www(例如 www.google.com),这可能吗?
提前谢谢。
更新
下面的字符串找到 http、https 和 www,但带有 www 类型的链接具有错误的 href。例如.com它链接到webroot/www.test。
'/((http[s]?:|www[.])[^'s]*)/'
溶液
/**
* Make clickable links from URLs in text.
*/
public function make_clickable($text) {
// Force http to www.
$text = preg_replace( "(www'.)", "http://www.", $text );
// Delete duplicates after force.
$text = preg_replace( "(http://http://www'.)", "http://www.", $text );
$text = preg_replace( "(https://http://www'.)", "https://www.", $text );
// The RegEx.
$regExUrl = "/(http|https)':'/'/[a-zA-Z0-9'-'.]+'.[a-zA-Z]{2,3}('/'S*)?/";
// Check if there is a URL in the text.
if(preg_match($regExUrl, $text, $url)) {
// Make the URLs hyper links.
$text = preg_replace(
$regExUrl,
'<a href="' . $url[0] . '" rel="nofollow" target="_blank">' . $url[0] . '</a>',
$text
);
}
return $text;
}
您有一些语法错误(没有逃脱/
)。无论如何,如果你想匹配www.
只需将其直接添加到你的字符串中(记住转义.
,否则这是一个控制字符)
preg_replace_callback(
'#'b(?<![href|src]=[''"])(?:http(?:s|):'/'/|)(?:www'.|)[^'s()<>]+(?:'(['w'd]+')|(?:[^[:punct:]'s]|'/))#', ...);