0

我有一个 textarea 字段,我希望允许用户输入任何文本(包括但不限于 url)。我为输入禁用了 html,因此不允许使用标签。我需要能够将这些类型的网址转换为链接:

http://example.com
www.example.com
example.com
http://example.com/path/to/something
http://example.com/path/to/something.php?v1=a&v2=b

或者基本上是用户可以从浏览器复制/粘贴的任何 url。我即将获得一个功能齐全的版本,但我的正则表达式无法与 www.example.com 文本一起正常工作。这是我正在使用的 PHP 代码:

// Convert links in a string to links
function linkify($str)
{   
    // Change www.example.com into http://www.example.com
    $str = str_replace('www.', 'http://www.', $str);
    $str = str_replace('http://http://www.', 'http://www.', $str);

    // Find and replace
    $exp = '@(http)?(s)?(://)?(([-\w]+\.)+([^\s]+)+[^,.\s])@';
    preg_match_all($exp, $str, $matches);
    $matches = array_unique($matches[0]);
    foreach($matches as $match) 
    {
        $replacement = '<a href="'.$match.'">'.$match.'</a>';
        $str = str_replace($match, $replacement, $str);
    }
    return $str;
}

谁能帮我调整我的代码以使其与所有示例 url 一起工作?

4

0 回答 0