PHP: Regexp to change urls


PHP: Regexp to change urls

我正在寻找一个不错的regexp,它可以将字符串从:更改为

text text website.tld text text anotherwebsite.tld/longeraddress text http://maybeanotheradress.tld/file.ext

进入bbcodes

text text [url=website.tld]LINK[/url] text text [url=anotherwebsite.tld/longeradress]LINK[/url] text text [url=http://maybeanotheradress.tld/file/ext]LINK[/url]

你能给我建议吗?

即使我投票支持复制,一个普遍的建议是:分而治之

在输入字符串中,所有"URL"都不包含任何空格。因此,您可以将字符串划分为不包含空格的部分:

$chunks = explode(' ', $str);

正如我们所知,每个部分现在都可能是一个链接,您可以创建自己的函数,它可以告诉我们:

/**
 * @return bool
 */
function is_text_link($str)
{
    # do whatever you need to do here to tell whether something is
    # a link in your domain or not.
    # for example, taken the links you have in your question:
    $links = array(
        'website.tld', 
        'anotherwebsite.tld/longeraddress', 
        'http://maybeanotheradress.tld/file.ext'
    );
    return in_array($str, $links);
}

in_array只是一个例子,您可能正在寻找基于正则表达式的模式匹配。您可以稍后对其进行编辑以满足您的需要,我将此作为练习。

正如你现在可以说什么是链接,什么不是,剩下的唯一问题是如何从链接中创建BBCode,这是一个相当简单的字符串操作:

 if (is_link($chunk))
 {
     $chunk = sprintf('[url=%s]LINK[/url]', $chunk);
 }

因此,从技术上讲,所有问题都已经解决,这需要放在一起:

function bbcode_links($str)
{
    $chunks = explode(' ', $str);
    foreach ($chunks as &$chunk)
    {
        if (is_text_link($chunk))
        {
             $chunk = sprintf('[url=%s]LINK[/url]', $chunk);
        }              
    }
    return implode(' ', $chunks);
}

这已经与您的示例字符串一起运行了(演示):

$str = 'text text website.tld text text anotherwebsite.tld/longeraddress text http://maybeanotheradress.tld/file.ext';
echo bbcode_links($str);

输出:

text text [url=website.tld]LINK[/url] text text [url=anotherwebsite.tld/longeraddress]LINK[/url] text [url=http://maybeanotheradress.tld/file.ext]LINK[/url]

然后,您只需要调整is_link函数即可满足您的需求。玩得高兴