PHP:使用正则表达式更改 url
我正在寻找好的正则表达式,它可以将我的字符串从:
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]
您能提供建议吗?
I'm looking for nice regexp which could change me string from:
text text website.tld text text anotherwebsite.tld/longeraddress text http://maybeanotheradress.tld/file.ext
into 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]
Could you please advice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
即使我投票支持重复,一般性建议:分而治之。
在您的输入字符串中,所有“URL”都不包含任何空格。因此,您可以将字符串划分为不包含空格的部分:
正如我们所知,每个部分现在都可能是一个链接,您可以创建自己的函数来说明这一点:
in_array
只是一个示例,您可能正在寻找基于正则表达式的模式匹配。您可以稍后对其进行编辑以满足您的需要,我将其保留为练习。正如您现在可以说出链接是什么和不是什么一样,剩下的唯一问题是如何从链接创建 BBCode,这是一个相当简单的字符串操作:
因此从技术上讲,所有问题都已解决,需要将其放在一起:
这已经与您有问题的示例字符串一起运行(演示):
输出:
然后您只需要调整您的
is_link
功能来满足您的需求。玩得开心!Even I vote for duplicate, a general suggestion: Divide and Conquer.
In your input string, all "URLs" do not contain any spaces. So you can divide the string into the parts that do not contain spaces:
As we know that each part is now potentially a link you can create your own function that is able to tell so:
The
in_array
is just an example, you might be looking for regular expression based pattern matching instead. You can edit it later to fit your needs, I leave this as an exercise.As you can now say what a link is and what not, the only problem left is how to create a BBCode out of a link, that's a fairly simple string operation:
So technically, all problems have been solved and this needs to be put together:
This already runs with your example string in question (Demo):
Output:
You then only need to tweak your
is_link
function to fullfill your needs. Have fun!