[
和
]
是正则表达式中的特殊字符,用于列举匹配的字符。
[a-z]
匹配
a
到
z
之间的任何小写字母。
[03b]
匹配 "0"、"3" 或 "b"。如果要匹配字符
[
和
]
,需要在它们前面加上
\
进行转义。
你的代码当前表示“用空字符串替换任何 []().
的字符”(为了更清晰地排列顺序而重新排列了顺序)。
贪婪匹配:
preg_replace('/\[.*\]/', '', $str); // Replace from one [ to the last ]
贪婪匹配可能会匹配多个 [ 和 ]。该表达式将接受 an example [of "sneaky"] text [with more "sneaky"] here
并将其转换为 an example here
。
Perl 有一种非贪婪匹配的语法(你很可能不想贪婪):
preg_replace('/\[.*?\]/', '', $str);
非贪婪匹配尽量少地匹配字符。以同样的例子为例:an example [of "sneaky"] text [with more "sneaky"] here
变成 an example text here
。
只匹配到第一个后面的]:
preg_replace('/\[[^\]]*\]/', '', $str); // Find a [, look for non-] characters, and then a ]
这种写法更加明确,但难以阅读。使用相同的示例文本,您将获得非贪婪表达式的输出。
请注意,这些都不会显式处理空格。左右两侧的空格[
和]
将保留。
还要注意,所有这些方法在遇到格式错误的输入时都可能失败。多个[
和]
没有匹配可能会导致出人意料的结果。