gpt4 book ai didi

php - 如何在 PHP 中使用正则表达式清除括号之间的文本?

转载 作者:行者123 更新时间:2023-12-02 22:04:23 25 4
gpt4 key购买 nike

问题Remove Text Between Parentheses PHP有效,但仅适用于“完整”括号(开始和结束):

preg_replace('/\([^)]+\)/', '', $myString);

但我也需要它来处理未闭合的括号。例如:

$string1 = 'Something (unimportant stuff'; //Becomes 'Something '
$string2 = '(unimportant stuff'; //Becomes '' (empty string)
$string3 = 'Something (bad) happens'; //Becomes 'Something happens'
$string4 = 'Something)'; //Stays the same

我真的不在乎我是否必须通过两遍(使用原始答案和新答案)...

最佳答案

您可以将最后的右括号设为可选:

preg_replace('/\([^)]+\)?/', '', $myString);
^

关于php - 如何在 PHP 中使用正则表达式清除括号之间的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16361957/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com