Hi All,
I have a pattern like this:
RS-1.75 m(TE)
from which, I want to select string from round brackets ( in this case, TE). Can anyone help me in regex or any other way to do this?
Thanks,
select string from round bracket
Moderator: General Moderators
-
rahulsonar
- Forum Newbie
- Posts: 10
- Joined: Wed Mar 11, 2009 8:54 am
Re: select string from round bracket
Code: Select all
$string = "This is a (IE) test about the this (UY)";
preg_match_all("/\((.*)\)/U",$string,$results);
foreach ($results[1] as $ID ) print $ID . "<BR>";Re: select string from round bracket
Thank you for this response. I had the very same question. This looks like it would work, but I am a little confused about the /U modifier. It seems that this would cause some problems, I might be wrong about this. Is there another approach that I can take in this situation, or is this the best way? I will need to work this issue out before I can move forward on the human resource management software that I have under development. As of now, this little snippet is causing bugs all over the place, so hopefully someone has some helpful advice. Thank you.
Last edited by Tosha on Wed Jan 04, 2012 9:20 am, edited 1 time in total.
Re: select string from round bracket
Yes, ouchiko's pattern works, but...
I would not recommend it.
Why? Because it uses an uncommon (and potentially confusing) modifier: /U
This pattern modifier says "swap the greediness status of the star and question mark quantifiers". So in this expression, the "greedy star" is lazy!!! That means you have a non-standard regex that will break almost everywhere except in this particular context.
Making only slight modifications to ouchiko's code, I would suggest something much more conventional:
In the capturing parentheses, instead of capturing everything, we capture anything that is not a closing parenthesis.
Note: This is only a starting point on the wide topic of capturing the content inside parentheses. For nested sets of parentheses, you may have to use a recursive regex.
Wishing you all a beautiful end of the year.
I would not recommend it.
Why? Because it uses an uncommon (and potentially confusing) modifier: /U
This pattern modifier says "swap the greediness status of the star and question mark quantifiers". So in this expression, the "greedy star" is lazy!!! That means you have a non-standard regex that will break almost everywhere except in this particular context.
Making only slight modifications to ouchiko's code, I would suggest something much more conventional:
Code: Select all
<?php
$string = "This is a (IE) test about the this (UY)";
preg_match_all(",\(([^)]*)\),",$string,$results);
foreach ($results[1] as $ID ) print $ID . "<br />";
?>Note: This is only a starting point on the wide topic of capturing the content inside parentheses. For nested sets of parentheses, you may have to use a recursive regex.
Wishing you all a beautiful end of the year.