Метод ниже делает ссылки кликабельными. Это фильтр. Вы отправляете текстовую строку, и она преобразует 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 эм>. Например, он ссылается на webroot/www.test.com.
'/((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;
}