我无法帮助您解决 URL 修复问题,但我可以解决以下问题...
用正则表达式匹配方括号
在正则表达式中,方括号:[]
是元字符(用于定义字符类)。要匹配目标字符串中的方括号(或任何其他正则表达式元字符),您需要在正则表达式模式内使用反斜杠对其进行转义。因此要匹配: [tag]
,模式需要是: \[tag\]
。(实际上,右方括号在技术上不是元字符,但无论如何我都喜欢转义它 - 这没有害处,并且更好地传达了我们打算匹配文字的含义:]
。)
PHP函数:attachment2img()
以下经过测试的 PHP 函数将所有:[attachment]file.jpg[/attachment]
标签转换为:[img]file.jpg[/img]
标签。请注意,此功能仅更改内容以: .jpg
、.jpeg
和结尾.gif
的附件标签.png
(将它们限制为仅图像文件)。
function attachment2img($text) {
return preg_replace('%
# Match a [attachment]image.jpg[/attachment] construct.
\[attachment\] # ATTACHMENT open tag.
( # $1: ATTACHMENT contents.
[^[\]]+ # Image URL up to extension.
\. # Extension separated with a dot.
(?: # Group of allowed image extensions:
jpe?g # Either a .jpg or .jpeg,
| gif # or a .gif,
| png # or a .png extension.
) # End group of allowed image extensions.
) # End $1: ATTACHMENT contents.
\[/attachment\] # ATTACHMENT close tag.
%ix', '[img]$1[/img]', $text);
}
上面的正则表达式是在自由跨度模式下编写的,并且有完整的注释(注意模式字符串末尾的:'x' 标志修饰符)。所有重要的正则表达式都应该以这种方式编写,以提高可读性和可维护性。
示例输入:
These should match:
stuff [attachment]simplefile.jpg[/attachment] more stuff.
stuff [attachment]relative/path/file.jpeg[/attachment] more stuff.
stuff [attachment]http://domain.com/path/file.gif[/attachment] more stuff.
These should NOT match:
stuff [attachment]file.zip[/attachment] more stuff.
stuff [attachment]file_jpg[/attachment] more stuff.
stuff [attachment]file.jpg.txt[/attachment] more stuff.
stuff [attachment]file.nonimage[/attachment] more stuff.
示例输出:
These should match:
stuff [img]simplefile.jpg[/img] more stuff.
stuff [img]relative/path/file.jpeg[/img] more stuff.
stuff [img]http://domain.com/path/file.gif[/img] more stuff.
These should NOT match:
stuff [attachment]file.zip[/attachment] more stuff.
stuff [attachment]file_jpg[/attachment] more stuff.
stuff [attachment]file.jpg.txt[/attachment] more stuff.
stuff [attachment]file.nonimage[/attachment] more stuff.
希望这会给您一个良好的开端。