如何使用php将textarea中的链接转换为link-element?

时间:2011-06-01 16:32:19

标签: php html string

我正在创建一个脚本并且它包含一个发布脚本但我希望用户直接从其他任何地方复制链接,当他们发布链接文本时,链接文本应自动将链接转换为link-element(<a>

例如:

Ask this on http://stackoverflow.com now

成为

Ask this on <a href="http://stackoverflow.com">http://stackoverflow.com</a> now

我尝试了str_replace()功能,但这不是解决方案。

有谁能告诉我这方面的解决方案?

2 个答案:

答案 0 :(得分:4)

对此有几种解决方案,其中大部分都写得不好而且不完整。在这种情况下,我建议使用一个已经存在的大框架解决方案,没有必要重新发明轮子。

例如,this article on Zenverse描述了WordPress处理此问题的方式。

让我在这里添加片段以供进一步参考:

function _make_url_clickable_cb($matches) {
    $ret = '';
    $url = $matches[2];

    if ( empty($url) )
        return $matches[0];
    // removed trailing [.,;:] from URL
    if ( in_array(substr($url, -1), array('.', ',', ';', ':')) === true ) {
        $ret = substr($url, -1);
        $url = substr($url, 0, strlen($url)-1);
    }
    return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $ret;
}

function _make_web_ftp_clickable_cb($matches) {
    $ret = '';
    $dest = $matches[2];
    $dest = 'http://' . $dest;

    if ( empty($dest) )
        return $matches[0];
    // removed trailing [,;:] from URL
    if ( in_array(substr($dest, -1), array('.', ',', ';', ':')) === true ) {
        $ret = substr($dest, -1);
        $dest = substr($dest, 0, strlen($dest)-1);
    }
    return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>" . $ret;
}

function _make_email_clickable_cb($matches) {
    $email = $matches[2] . '@' . $matches[3];
    return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
}

function make_clickable($ret) {
    $ret = ' ' . $ret;
    // in testing, using arrays here was found to be faster
    $ret = preg_replace_callback('#([\s>])([\w]+?://[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]*)#is', '_make_url_clickable_cb', $ret);
    $ret = preg_replace_callback('#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]*)#is', '_make_web_ftp_clickable_cb', $ret);
    $ret = preg_replace_callback('#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret);

    // this one is not in an array because we need it to run last, for cleanup of accidental links within links
    $ret = preg_replace("#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i", "$1$3</a>", $ret);
    $ret = trim($ret);
    return $ret;
}

链接文章中所写的示例用法:

$string = 'I have some texts here and also links such as http://www.youtube.com , www.haha.com and lol@example.com. They are ready to be replaced.';

echo make_clickable($string);

答案 1 :(得分:1)

您需要的是首先找到链接的子串。为此,您可以使用正则表达式。然后,您需要在链接周围添加html标记。 preg_replace应该是你的朋友。

例如(简化示例):

$linkedtext = preg_replace ( '@\bhttp://([a-zA-Z0-9.%/]+)\b@', '<a href="http://$1">$1</a>', $text)

要获得更好的匹配正则表达式的网址,请参阅Regex to match URL

相关问题