Regular expression to remove multiple parenthesis

怎甘沉沦 提交于 2019-12-25 07:54:43

问题


I'm in need of a regular expression that can remove unnecessary/extra parenthesis in a string if found.

Example:

Bob Barker LIVE! (((Don't Miss out!)))

Wanted Result:

Bob Barker LIVE! (Don't Miss out!)

I don't care if users you them, as long as they don't over use them, and make sure to close them.

Thanks for any feedback.


回答1:


That's easy enough.

preg_replace('~[\(\)]+~', '', $string);

Edit: I didn't read your whole question. You still want parenthesis, just not duplicates.

preg_replace(array('~\(+~', '~\)+~'), array('(', ')'), $string);



回答2:


You can do this effectively with regex + recursion. Do this until it stops doing anything:

s/\(\([^()]*)\)\)/\(\1\)/g

Now some comments:

1) I'm leaving it to you to convert sed/perl style into PHP style regex.

2) It's hard to read because ( ) are special characters. Basically I'm saying "replace every ((...)) with (...) as long as ... doesn't contain any ( or ). And to be honest I didn't test the mess I wrote down, but with this idea you should be able to repair.

This always removes them in pairs.

Basically the moral here is: you asked a question you can't do with a simple regex - removing in pairs requires more state than the language permits. But this one is low-hanging fruit if you iterate over the simple regex and eat the doubles from inside-out.




回答3:


Try this:

preg_replace( '/\(+(.*?)\)+/', '($1)', 'Bob Barker LIVE! (((Don\'t Miss out!)))');

Demo




回答4:


This won't work properly for nested parentheses, but that's really difficult to get right with regex (and depending on the engine even impossible):

preg_replace(array('/\(+/', '/\)+/'), array('(', ')'), $text);



回答5:


You can try this :

preg_replace("([\\(]{1,})", "(", preg_replace("([\\)]{1,})", ")", $your_string));


来源:https://stackoverflow.com/questions/10999835/regular-expression-to-remove-multiple-parenthesis

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