如何从方括号和括号本身之间删除文本?
例如,我需要:
hello [quote="im sneaky"] world
变成:
hello world
这是我正在尝试使用的,但它没有起到作用:
preg_replace("/[\[(.)\]]/", '', $str);
我刚刚结束了:
hello quote="im sneaky" world
最佳答案
[
和 ]
是正则表达式中的特殊字符。它们用于列出匹配的字符。 [a-z]
匹配 a
和 z
之间的任何小写字母。 [03b]
匹配“0”、“3”或“b”。要匹配字符 [
和 ]
,您必须使用前面的 \
对它们进行转义。
您的代码当前表示“将 []().
的任何字符替换为空字符串”(为清楚起见,按照您键入它们的顺序重新排序)。
贪心匹配:
preg_replace('/\[.*\]/', '', $str); // Replace from one [ to the last ]
贪心匹配可以匹配多个 [s 和 ]s。该表达式将采用 一个示例 [of "sneaky"] 文本 [with more "sneaky"] here
并将其转换为 an example here
。
Perl 有一个非贪婪匹配的语法(你很可能不想贪婪):
preg_replace('/\[.*?\]/', '', $str);
非贪婪匹配 try catch 尽可能少的字符。使用相同的例子: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 ]
这更明确,但更难阅读。使用相同的示例文本,您将获得非贪婪表达式的输出。
请注意,这些都没有明确处理空白。 [
和 ]
两边的空格将保留。
另请注意,所有这些都可能因格式错误的输入而失败。没有匹配项的多个 [
和 ]
可能会导致令人惊讶的结果。
关于php - 如何使用正则表达式删除方括号和它们之间的任何内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2359921/