删除括号外的文字

发布于 2024-10-21 11:29:10 字数 188 浏览 2 评论 0原文

$text = 'remove this text (keep this text and 123)';

echo preg_replace('', '', $text);

它应该输出:

(keep this text and 123)

i.e.

$text = 'remove this text (keep this text and 123)';

echo preg_replace('', '', $text);

It should output:

(keep this text and 123)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

后eg是否自 2024-10-28 11:29:10

这将做到这一点:(并且也适用于嵌套 ()

$re = '/[^()]*+(\((?:[^()]++|(?1))*\))[^()]*+/';
$text = preg_replace($re, '$1', $text);

以下是几个测试用例:

Input:
Non-nested case: 'remove1 (keep1) remove2 (keep2) remove3'
Nested case:     'remove1 ((keep1) keep2 (keep3)) remove2'

Output:
Non-nested case: '(keep1)(keep2)'
Nested case:     '(keep1) keep2 (keep3)'

This will do it: (and works with nested () as well)

$re = '/[^()]*+(\((?:[^()]++|(?1))*\))[^()]*+/';
$text = preg_replace($re, '$1', $text);

Here are a couple test cases:

Input:
Non-nested case: 'remove1 (keep1) remove2 (keep2) remove3'
Nested case:     'remove1 ((keep1) keep2 (keep3)) remove2'

Output:
Non-nested case: '(keep1)(keep2)'
Nested case:     '(keep1) keep2 (keep3)'
魂ガ小子 2024-10-28 11:29:10

获取括号内找到的任何内容,将其放入捕获组中并仅保留它,如下所示:

echo preg_replace('/^.*(\(.*\)).*$/', '$1', $text);

Take anything found within the brackets, put it in a capture group and keep that only, like this:

echo preg_replace('/^.*(\(.*\)).*$/', '$1', $text);
段念尘 2024-10-28 11:29:10

这里是“非 preg_replace”方式:

<?

$text = 'remove this text (keep this text)' ;

$start = strpos($text,"(") ; 
$end = strpos($text,")") ; 

echo substr($text,$start+1,$end-$start-1) ; // without brackets
echo substr($text,$start,$end-$start+1) ; // brackets included

?>

注意:
- 这仅提取第一对括号。
- 将 strpos() 替换为 strrpos() 以获得最后一对括号。
- 嵌套的括号会引起麻烦。

Here the 'non preg_replace' way:

<?

$text = 'remove this text (keep this text)' ;

$start = strpos($text,"(") ; 
$end = strpos($text,")") ; 

echo substr($text,$start+1,$end-$start-1) ; // without brackets
echo substr($text,$start,$end-$start+1) ; // brackets included

?>

Note:
- This extracts only the first pair of brackets.
- Replace strpos() with of strrpos() to get the last pair of brackets.
- Nested brackets cause trouble.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文