$string = "this (is (a) test) with (two parenthesis) duh";
Đối với một chuỗi như thế này bạn có thể sử dụng và sử dụng preg_match_all nổ tung.
$string = "this (is (a) test) with (two parenthesis) duh";
$regex = '#\((([^()]+|(?R))*)\)#';
if (preg_match_all($regex, $string ,$matches)) {
echo implode(' ', $matches[1]);
} else {
//no parenthesis
echo $string;
}
Hoặc bạn có thể sử dụng preg_replace, nhưng với nhiều dấu ngoặc đơn, bạn sẽ mất khoảng trắng giữa chúng.
$regex = '#[^()]*\((([^()]+|(?R))*)\)[^()]*#';
$replacement = '\1';
echo preg_replace($regex, $replacement, $string);
Tôi nhận được rất nhiều trợ giúp từ trang này, Finer points of PHP regular expressions.
Bản sao có thể có của [PHP: Cách tốt nhất để trích xuất văn bản trong ngoặc đơn?] (Https://stackoverflow.com/questions/196520/php-best-way-to-extract-text-within-parenthesis) – EdChum