I found this code posted on SO to change text links into hyperlinks:と一致する正規表現と<a href>?
function auto_link_text($text)
{
$pattern = '#\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))#';
$callback = create_function('$matches', '
$url = array_shift($matches);
$url_parts = parse_url($url);
$text = parse_url($url, PHP_URL_HOST) . parse_url($url, PHP_URL_PATH);
$text = preg_replace("/^www./", "", $text);
$last = -(strlen(strrchr($text, "/"))) + 1;
if ($last < 0) {
$text = substr($text, 0, $last) . "…";
}
return sprintf(\'<a rel="nowfollow" href="%s">%s</a>\', $url, $text);
');
return preg_replace_callback($pattern, $callback, $text);
}
However, it seems to change them into hyperlinks even if they are already a part of a hyperlink so you end up with something like <a href="<a href
(etc). I figure what I could do is check for an already formatted hyperlink and if I don't find one, I can do that function. Or even put the check in the function. So something like:
function auto_link_text($text)
{
if preg_match(proper stuff in here){
return $text;
}else{
$pattern = '#\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))#';
$callback = create_function('$matches', '
$url = array_shift($matches);
$url_parts = parse_url($url);
$text = parse_url($url, PHP_URL_HOST) . parse_url($url, PHP_URL_PATH);
$text = preg_replace("/^www./", "", $text);
$last = -(strlen(strrchr($text, "/"))) + 1;
if ($last < 0) {
$text = substr($text, 0, $last) . "…";
}
return sprintf(\'<a rel="nowfollow" href="%s">%s</a>\', $url, $text);
');
return preg_replace_callback($pattern, $callback, $text);
}
}
Or perhapse the regex in the function should be changed.
possible duplicate of [Automatically convert keywords to links in php](http://stackoverflow.com/questions/9929953/automatically-convert-keywords-to-links-in-php) – Anthony
Check out my [answer](http://stackoverflow.com/questions/9929953/automatically-convert-keywords-to-links-in-php/9932767#9932767). – Anthony
[Possible duplicate](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – c69