php: regex remove bracket in string

2019-02-27 05:05发布

similiar like this example, php: remove brackets/contents from a string? i have no idea to replace

$str = '(ABC)some text'

into

$str = 'ABC';

currently use $str = preg_replace('/(.)/','',$str); but not works. how to fix this?

4条回答
放荡不羁爱自由
2楼-- · 2019-02-27 05:50

If you want to use replace, you could use the following:

 $str = "(ABC)some text";
 $str = preg_replace("/^.*\(([^)]*)\).*$/", '$1', $str);

The pattern will match the whole string, and replace it with whatever it found inside the parenthesis

查看更多
仙女界的扛把子
3楼-- · 2019-02-27 05:52

Instead of preg_replace, I would use preg_match:

preg_match('#\(([^)]+)\)#', $str, $m);
echo $m[1];
查看更多
闹够了就滚
4楼-- · 2019-02-27 05:55

Try this:

$str = preg_replace('/\((.*?)\).*/','\\1',$str);
查看更多
欢心
5楼-- · 2019-02-27 06:05

I'd avoid using regex altogether here. Instead, you could use normal string functions like this: $str = str_replace(array('(',')'),array(),$str);

查看更多
登录 后发表回答