【问题标题】:PHP: Regexp to change urlsPHP:正则表达式更改网址
【发布时间】:2012-02-25 15:06:55
【问题描述】:

我正在寻找可以改变我的字符串的漂亮正则表达式:

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]

你能指点一下吗?

【问题讨论】:

  • 你将如何区分文本和网站地址?
  • 首先我想通过分隔符分割字符串:“:”、“-”和空格键
  • @AdrianK。 “hi.com whit me”(写得不好的短语的例子)。鉴于您当前的规则,hi.com 应被解释为 URL。我建议强制 URL 以协议为前缀。
  • @ArianK:这个问题已经被问过无数次了,即使在今天也是如此。请使用搜索,有不同的方法可以做到这一点,最终它不取决于您是插入 BBCODE 还是仅插入 HTML A 标签。

标签: php regex url replace bbcode


【解决方案1】:

即使我投票赞成重复,一般建议:分而治之

在您的输入字符串中,所有“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 函数即可满足您的需求。玩得开心!

【讨论】:

    猜你喜欢
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多