1

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!!

Joel
  • 199
  • 2
  • 10
  • 1
    You're telling me you didn't check the contents of `$matches`!? – Nick Apr 03 '11 at 21:36
  • @Nick: I do understand why you threw a "stupid" rock at me. I didn't specify that I was using this script through Asterisk, which does not permit the use of "var_dump" - Admittedly I could have used other mechanisms to check the contents of the array, but I simply didn't think of it. But we all have to learn through experience. So thank you for your insight. – Joel Apr 04 '11 at 11:14

2 Answers2

7

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.

Khez
  • 10,172
  • 2
  • 31
  • 51
3

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);
intuited
  • 23,174
  • 7
  • 66
  • 88