1

我想问2个关于php中url转换的问题。

1 个问题:我需要将文本转换为链接。我已经完成了自己的 preg 并且还阅读了许多论坛,但所有解决方案都与 www 连接。或 (ht|f)tp(s),但我需要 preg 来转换域名,即使文本中没有 www 和 http,例如:

I like stackoverflow.com very much

进入

I like <a href='http://stackoverflow.com'>stackoverflow.com</a> very much

当然它必须考虑点和逗号等,例如:

I like stackoverflow.com.

进入

I like <a href='http://stackoverflow.com'>stackoverflow.com</a>.

还有一个问题:wiki 上带有 url 编码符号的链接按原样显示,但在其他网站上,它们显示为 url 编码字符串 (%XX%XX%XX)。维基是如何做到这一点的?谢谢!

4

2 回答 2

0

auto_linkfrom函数CodeIgniter URL helper可以帮助你:

if ( ! function_exists('auto_link'))
{
    function auto_link($str, $type = 'both', $popup = FALSE)
    {
        if ($type != 'email')
        {
            if (preg_match_all("#(^|\s|\()((http(s?)://)|(www\.))(\w+[^\s\)\<]+)#i", $str, $matches))
            {
                $pop = ($popup == TRUE) ? " target=\"_blank\" " : "";

                for ($i = 0; $i < count($matches['0']); $i++)
                {
                    $period = '';
                    if (preg_match("|\.$|", $matches['6'][$i]))
                    {
                        $period = '.';
                        $matches['6'][$i] = substr($matches['6'][$i], 0, -1);
                    }

                    $str = str_replace($matches['0'][$i],
                                        $matches['1'][$i].'<a href="http'.
                                        $matches['4'][$i].'://'.
                                        $matches['5'][$i].
                                        $matches['6'][$i].'"'.$pop.'>http'.
                                        $matches['4'][$i].'://'.
                                        $matches['5'][$i].
                                        $matches['6'][$i].'</a>'.
                                        $period, $str);
                }
            }
        }

        if ($type != 'url')
        {
            if (preg_match_all("/([a-zA-Z0-9_\.\-\+]+)@([a-zA-Z0-9\-]+)\.([a-zA-Z0-9\-\.]*)/i", $str, $matches))
            {
                for ($i = 0; $i < count($matches['0']); $i++)
                {
                    $period = '';
                    if (preg_match("|\.$|", $matches['3'][$i]))
                    {
                        $period = '.';
                        $matches['3'][$i] = substr($matches['3'][$i], 0, -1);
                    }

                    $str = str_replace($matches['0'][$i], safe_mailto($matches['1'][$i].'@'.$matches['2'][$i].'.'.$matches['3'][$i]).$period, $str);
                }
            }
        }

        return $str;
    }
}
于 2013-04-19T14:31:03.950 回答
0

对于您的第一个问题,我不建议您这样做,很难知道包含点的单词是否是域名,并且人们经常忘记在段落中间的点后放一个空格.

对于您的第二个问题,这很简单,您对 href 中的链接进行 url 编码,但不在打开和关闭标签之间。例如 :

<a href="http://site.na/test.php?t=sqdl%2654%22dfd%C2%B0%3D%2B">http://site.na/test.php?t=sqdl&54"dfd°=+</a>
于 2013-04-19T14:31:59.740 回答