PHP BB代码和链接
好的。所以我正在构建一个函数,它将 bbcoded 字符串解析为 html。 BBCode 链接的结构如下:
[url=http://somelink.com/]Link[/url]
我想要这样做:
<a href="http://somelink.com/">Link</a>
但我也想检查链接是否有效,以保护自己免受 XSS 侵害。我发现这个正则表达式来检查有效链接:
/(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
现在,我尝试 preg_match_all $str 和 foreach 匹配来检查它的 url 是否有效,然后将其解析为 html,但似乎我无法做到这一点。有什么建议吗?
OK. So I am building a function that will parse a bbcoded string to html. The structure of the BBCode link is like so:
[url=http://somelink.com/]Link[/url]
And I want to make it:
<a href="http://somelink.com/">Link</a>
But I also want to check if the link is valid, to protect myself from XSS. I found this regex to check for valid link:
/(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
And now, I tried to preg_match_all the $str and foreach match to check if it's url is valid and then to parse it to html, but it seems that I can't do it. Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看一下 PHP 的内置 Filter 模块。它从 PHP 5.2 开始可用,并包含用于过滤有效 URL 的
FILTER_VALIDATE_URL
常量。请参阅一些使用示例。个人从未使用过此功能,但我相信在您的情况下,依赖语言内置功能比使用正则表达式安全得多(因为您似乎并不精通正则表达式)。
Take a look at PHP's built-in Filter module. It's available since PHP 5.2 and contains
FILTER_VALIDATE_URL
constant to filter valid urls. See some usage examples.Never used this personally, but I believe relaying on language built-in capabilities is much safer than using regexes in your case (since you don't seem regex-proficient).
为什么要重新发明轮子?
您可以使用PECL扩展来解析BBCode
Why re-invent the wheel?
You can use the PECL extension to parse BBCode