Remove the text outside the brackets

匿名 (未验证) 提交于 2019-12-03 02:31:01

问题:

i.e.

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

It should output:

(keep this text and 123) 

回答1:

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

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


回答2:

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)' 


回答3:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!