The method below make links clickable. It's a filter. You send the text string and it convert http and https into clickable links.
/**
* 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);
}
I want to extend this method to accept www as well (ex www.google.com), it this possible?
Thanks in advance.
UPDATE
The below string finds http, https and www, but links with type www have the wrong href. It links to webroot/www.test.com for example.
'/((http[s]?:|www[.])[^\s]*)/'
SOLUTION
/**
* 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;
}
You have some syntax errors (didn't escape the
/
). At any rate, if you want to matchwww.
just add it into your string directly (remembering to escape the.
, which is a control character otherwise)