删除括号之间的文本 PHP
我只是想知道如何在 php.ini 中删除一组括号之间的文本以及括号本身。
示例:
ABC (Test1)
我希望删除 (Test1) 并只留下 ABC
谢谢
I'm just wondering how I could remove the text between a set of parentheses and the parentheses themselves in php.
Example :
ABC (Test1)
I would like it to delete (Test1) and only leave ABC
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
preg_replace
是一个基于 Perl 的正则表达式替换例程。此脚本的作用是匹配所有出现的左括号,后跟任意数量的字符非右括号,然后再次跟上右括号,然后删除它们:正则表达式细分:
preg_replace
is a perl-based regular expression replace routine. What this script does is matches all occurrences of a opening parenthesis, followed by any number of characters not a closing parenthesis, and again followed by a closing parenthesis, and then deletes them:Regular expression breakdown:
接受的答案对于非嵌套括号非常有用。对正则表达式的轻微修改使其可以处理嵌套括号。
The accepted answer works great for non-nested parentheses. A slight modification to the regex allows it to work on nested parentheses.
没有正则表达式
without regex
它的工作原理是循环遍历每个字符,计算括号的数量。仅当
$paren_num == 0
(当它位于所有括号之外时)才会将字符附加到我们的结果字符串$new_string
中。It works by looping through each character, counting parentheses. Only when
$paren_num == 0
(when it is outside all parentheses) does it append the characters to our resulting string,$new_string
.最快速的方法(不带 preg):
如果您不想修剪单词末尾的空格,只需从代码中删除修剪功能即可。
Most quik method (without preg):
If you don't want to trim spaces at end of word, just remove trim function from code.
各位,正则表达式不能用于解析非正则语言。非常规语言是那些需要状态来解释的语言(即记住当前有多少个括号)。
上述所有答案都将在此字符串上失败:“ABC (hello (world) how are you)”。
阅读 Jeff Atwood 的《Parsing Html The Cthulhu Way》:https://blog.codinghorror。 com/parsing-html-the-cthulhu-way/,然后使用手动编写的解析器(循环遍历字符串中的字符,查看该字符是否是括号,维护一个堆栈)或者使用能够解析上下文无关语言的词法分析器/解析器。
另请参阅这篇关于“正确匹配括号的语言:”的维基百科文章 https://en.wikipedia.org /wiki/Dyck_language
Folks, regular expressions CANNOT be used to parse non-regular languages. Non-regular languages are those that require state to interpret (i.e. remembering how many parenthesis are currently open).
All of the above answers will fail on this string: "ABC (hello (world) how are you)".
Read Jeff Atwood's Parsing Html The Cthulhu Way: https://blog.codinghorror.com/parsing-html-the-cthulhu-way/, and then use either a by-hand written parser (loop through the characters in the string, see if the character is a parenthesis or not, maintain a stack) or use a lexer/parser capable of parsing a context-free language.
Also see this wikipedia article on the "language of properly matched parenthesis:" https://en.wikipedia.org/wiki/Dyck_language