[英]Replacing all type of BBCODE image links into HTML image links
I have this script for replacing BBCODE image tags to HTML tags 我有这个脚本可以将BBCODE图像标签替换为HTML标签
$text = "[img]https://somelink/2/3/pic.jpg[/img]
[img]https://somelink/2/3/pic.jpg[/img]
[img]https://somelink/2/3/pic.jpg[/img]";
echo preg_replace(
'~\[img\](https?://.*?\.(?:jpg|jpeg|gif|png|bmp))\[/img\]~s',
'<img src="$1" alt="" />',
$text);
This forks for links, which ends up whit some of given extensions: .jpg
.jpeg
... 这分叉了链接,最终得到了某些给定的扩展名:
.jpg
.jpeg
...
But if link are like: [img]https://somelink/2/3/pic.jpg
?w=bla [/img]
但是如果链接是这样的:
[img]https://somelink/2/3/pic.jpg
?w = bla [/img]
Then this regex pattern fails. 然后,此正则表达式模式失败。
What would be appropriate pattern for all type of image links? 对于所有类型的图像链接,哪种模式合适? I tried:
我试过了:
~\\[img\\](https?://.*?\\.(?:jpg|jpeg|gif|png|bmp).*)\\[/img\\]~Us
But this also not works 但这也行不通
You can use 您可以使用
\[img\](https?://.*?\.(?:jpe?g|gif|png|bmp).*?)\[/img\]
\\[img\\]
- Matches [img]
\\[img\\]
-匹配[img]
(https?://.*?\\.(?:jpe?g|gif|png|bmp).*?)
- Matches URL containing any of above extensions (https?://.*?\\.(?:jpe?g|gif|png|bmp).*?)
-匹配包含以上任何扩展名的URL \\[/img\\]
- Matches [/img]
\\[/img\\]
-匹配[/img]
You can visualize regex here 您可以在此处可视化正则表达式
Note:- as you're using U
flag you can safely remove ?
注意:-当您使用
U
标志时,可以安全删除?
after quantifiers, ie 在量词之后,即
\[img\](https?://.*\.(?:jpe?g|gif|png|bmp).*)\[/img\]
If it is possible that the query string parameters can also contain [
or ]
you could match the question mark \\?
如果查询字符串参数也可以包含
[
或]
,则可以匹配问号\\?
followed by matching until you encounter [/img]
and make use of a possessive quantifier to prevent unnecessary backtracking 然后进行匹配,直到遇到
[/img]
并利用所有格修饰符来防止不必要的回溯
Explanation 说明
\[img\](https?://.*?\.(?:jpe?g|gif|png|bmp)(?:\?(?:[^[]++|\[(?!/img\]))*+)?)\[/img]
\\[img\\]
Match [img]
\\[img\\]
匹配[img]
(
Capturing group (
捕获组
https?://.*?
Match http with optional s, ://
and 0+ times any char non greedy ://
和0+匹配,以匹配任何非char字符 \\.(?:jpe?g|gif|png|bmp)
Match a dot and any of the listed options \\.(?:jpe?g|gif|png|bmp)
匹配点和任何列出的选项 (?:
Non capturing group (?:
非捕获组
\\?
Match ? (?:[^[]++|\\[(?!/img\\]))*+
Repeat 0+ times matching not [
or match [
when what is directly on the right is not /img]
(?:[^[]++|\\[(?!/img\\]))*+
重复0+次不匹配[
或匹配[
当直接在右边的不是/img]
)?
Close non capturing group and make it optional )
Close capturing group )
关闭捕获组 \\[/img]
Match [/img]
\\[/img]
匹配[/img]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.