PHP:Regexp更改URL
我正在寻找可以将我的字符串从:PHP:Regexp更改URL,php,regex,url,replace,bbcode,Php,Regex,Url,Replace,Bbcode,我正在寻找可以将我的字符串从: 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
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);
}
_数组中的只是一个例子,您可能会寻找基于正则表达式的模式匹配。您可以稍后编辑它以满足您的需要,我将此留作练习
正如您现在可以说什么是链接,什么不是链接一样,剩下的唯一问题是如何从链接中创建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);
}
这已经在您的示例字符串()中运行:
输出:
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
功能即可满足您的需求。玩得开心 如何区分文本和网站地址?首先,我想到了用分隔符“:”、“-”和a分隔字符串spacebar@AdrianK. “hi.com whit me”(写得不好的短语的例子)。根据您当前的规则,hi.com
应该被解释为URL。我建议强制URL以协议作为前缀。可能重复@ArianK:这已经被问过很多次了,即使是今天。请使用搜索,有不同的方法可以做到这一点,最终它并不取决于你是否插入BBCODE或只是一个HTML标签。
text text [url=website.tld]LINK[/url] text text [url=anotherwebsite.tld/longeraddress]LINK[/url] text [url=http://maybeanotheradress.tld/file.ext]LINK[/url]