繁体   English   中英

PHP:正则表达式更改URL

[英]PHP: Regexp to change urls

我正在寻找可以将我的字符串从以下位置更改的正则表达式:

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

变成bbcode

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);
}

这已经与您的问题示例字符串( Demo )一起运行:

$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函数即可满足您的需求。 玩得开心!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM