如何用正则表达式删除方括号及其之间的任何内容? [英] How to remove square brackets and anything between them with a regex?
问题描述
如何删除方括号和方括号之间的文本?
How can I remove text from between square brackets and the brackets themselves?
例如,我需要:
hello [quote="im sneaky"] world
成为:
hello world
这是我要使用的内容,但并没有解决问题:
Here's what I'm trying to use, but it's not doing the trick:
preg_replace("/[\[(.)\]]/", '', $str);
我刚结束:
hello quote="im sneaky" world
推荐答案
[
和]
是正则表达式中的特殊字符.它们用于列出比赛的字符. [a-z]
匹配a
和z
之间的任何小写字母. [03b]
匹配"0","3"或"b".要匹配字符[
和]
,必须用前面的\
对其进行转义.
[
and ]
are special characters in a regex. They are used to list characters of a match. [a-z]
matches any lowercase letter between a
and z
. [03b]
matches a "0", "3", or "b". To match the characters [
and ]
, you have to escape them with a preceding \
.
您的代码当前显示为用空字符串替换[]().
的任何字符"(为了清楚起见,从键入顺序进行了重新排序).
Your code currently says "replace any character of []().
with an empty string" (reordered from the order in which you typed them for clarity).
贪婪的比赛:
preg_replace('/\[.*\]/', '', $str); // Replace from one [ to the last ]
贪婪的匹配可以匹配多个[s和].该表达式将使用an example [of "sneaky"] text [with more "sneaky"] here
并将其转换为an example here
.
A greedy match could match multiple [s and ]s. That expression would take an example [of "sneaky"] text [with more "sneaky"] here
and turn it into an example here
.
Perl具有非贪婪匹配的语法(您很可能不想贪婪):
Perl has a syntax for a non-greedy match (you most likely don't want to be greedy):
preg_replace('/\[.*?\]/', '', $str);
非贪婪匹配尝试捕获尽可能少的字符.使用相同的示例:an example [of "sneaky"] text [with more "sneaky"] here
变为an example text here
.
Non-greedy matches try to catch as few characters as possible. Using the same example: an example [of "sneaky"] text [with more "sneaky"] here
becomes an example text here
.
仅以下第一个]:
preg_replace('/\[[^\]]*\]/', '', $str); // Find a [, look for non-] characters, and then a ]
这是更明确的,但更难阅读.使用相同的示例文本,您将获得非贪婪表达式的输出.
This is more explicit, but harder to read. Using the same example text, you'd get the output of the non-greedy expression.
请注意,这些都没有明确处理空白. [
和]
两侧的空格都将保留.
Note that none of these deal explicitly with white space. The spaces on either side of [
and ]
will remain.
还要注意,所有这些都可能因格式错误而失败.多个[
和]
不匹配可能会导致令人惊讶的结果.
Also note that all of these can fail for malformed input. Multiple [
s and ]
s without matches could cause a surprising result.
这篇关于如何用正则表达式删除方括号及其之间的任何内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!