如何使用正则表达式删除方括号及其之间的任何内容?
如何删除方括号之间和方括号本身的文本?
例如,我需要:
hello [quote="im sneaky"] world
成为:
hello world
这是我正在尝试使用的,但它没有达到目的:
preg_replace("/[\[(.)\]]/", '', $str);
我最终得到:
hello quote="im sneaky" world
How can I remove text from between square brackets and the brackets themselves?
For example, I need:
hello [quote="im sneaky"] world
to become:
hello world
Here's what I'm trying to use, but it's not doing the trick:
preg_replace("/[\[(.)\]]/", '', $str);
I just ended up with:
hello quote="im sneaky" world
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
[
和]
是正则表达式中的特殊字符。它们用于列出匹配的字符。[az]
匹配a
和z
之间的任何小写字母。[03b]
匹配“0”、“3”或“b”。要匹配字符[
和]
,您必须使用前面的\
对它们进行转义。您的代码当前显示“将
[]().
的任何字符替换为空字符串”(为了清楚起见,按照您键入的顺序重新排序)。贪婪匹配:
贪婪匹配可以匹配多个 [ 和 ]。该表达式将采用
此处的[“sneaky”]文本示例[以及更多“sneaky”]
并将其转换为此处的示例
。Perl 有一个非贪婪匹配的语法(你很可能不想贪婪):
非贪婪匹配尝试捕获尽可能少的字符。使用相同的示例:
这里的[“偷偷摸摸”]文本示例[更多“偷偷摸摸”]
变成了这里的示例文本
。仅到下面的第一个]:
这更明确,但更难阅读。使用相同的示例文本,您将获得非贪婪表达式的输出。
请注意,这些都没有明确处理空白。
[
和]
两侧的空格将保留。另请注意,所有这些都可能因格式错误的输入而失败。多个不匹配的
[
和]
可能会导致令人惊讶的结果。[
and]
are special characters in a regex. They are used to list characters of a match.[a-z]
matches any lowercase letter betweena
andz
.[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).Greedy match:
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 intoan example here
.Perl has a syntax for a non-greedy match (you most likely don't want to be greedy):
Non-greedy matches try to catch as few characters as possible. Using the same example:
an example [of "sneaky"] text [with more "sneaky"] here
becomesan example text here
.Only up to the first following ]:
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.以防万一您正在寻找递归删除:
这将转换为:
这个[文字[更多文字]]对此
Just in case you are looking for a recursive removal:
That will convert this:
to this:
我认为你实际上想要外括号的括号,因为它是一个组。方括号是一系列表达式。不知道如何在 SO 中输入它。
I think you actually want parens for your outer brackets since it's a group. square brackets are a range of expressions. Not sure how to type it in SO.