Joel
Joel

Reputation: 308

RegEx pattern to match a string between two characters, but exclude the characters

Greetings all,

I have yet another RegEx question. I have done hours of searching but apparently I have missed the one key article I need.

I need to use preg_match() in PHP to match a string that is between parenthesis, but NOT have the parenthesis show up in the result. I have seen examples of similar issues, but I believe my problem is different because it's actually parenthesis that I am dealing with, with is a meta character in RegEx. Any merit to that?

Anyways...

String is:

     "200 result=1 (SIP/100-00000033)"

Current code is:

preg_match("/\((.*)\)/s", $res, $matches);

$matches[0] becomes:

     "(SIP/100-00000033)"

What I WANT is:

     "SIP/100-00000033"

I apologize because I'm sure this is VERY simple but I'm just not grasping it. Would anyone care to educate me?

Thank you in advance!!

Upvotes: 1

Views: 3401

Answers (2)

intuited
intuited

Reputation: 24084

If you really want the full match to exclude the parentheses, you can use look-ahead and look-behind assertions:

preg_match('/(?<=\().*(?=\))/s', $res, $matches);

Upvotes: 3

Khez
Khez

Reputation: 10350

Well, it all refers to the way you group items in the regular expression. Your solution is actually correct, you're just using the wrong index for matches. Try:

$matches[1]

If that somehow gives errors, post'em and we'll fix.

Upvotes: 7

Related Questions