tags:

views:

77

answers:

5

I'm new to regex with PHP. How can I find the contents of the first parentheses with a string that is a couple of paragraphs long.

I'm assuming I have to use the preg_match function

+1  A: 
preg_match("/^.*?\(([^\)]+)\)/", $search_this_string, $matches, PREG_OFFSET_CAPTURE);
print_r($matches);

This assumes your parenthetically quoted string doesn't contain any escaped (in some way) closing parens.

theraccoonbear
thanks, What does PREG_OFFSET_CAPTURE do?
chris
Why the anchoring to start of string? preg_match stops matching after the first match is found.
arnsholt
habit, I suppose
theraccoonbear
+1  A: 

As long as you don't want to support matching parentheses, "/\\(([^()])\\)/" will do it.

If you want to support arbitrarily nested parens, the short answer is that you can't. This is due to the fact that regexes can't capture the kind of strings nested parens are (context-free languages). You'll need some kind of parser library to do that. But the simple version above should work just fine for most cases.

arnsholt
+1  A: 
<?php
$str = "The quick (brown fox) jumps (over) the (lazy) dog.";
$first_match = preg_replace('/.*?\((.+?)\).*/', '$1', $str);
var_dump($first_match);

string(9) "brown fox"

Note: doesn't work on nested parentheses.

Ben James
+1  A: 
$s = "

yada yada yada
yada
yada yada
yada (bada bada
bada bada

bada) yada yada yada
yada yada
yada yada yada
( yo yo )
";

preg_match('/\((.*?)\)/ms', $s, $m);
print_r($m[1]);

At the end of the preg match pattern, '/\((.*?)\)/ms', the 'm' says multiline, and the 's' says "let the dot mean newline too".

Ewan Todd
+2  A: 

no need regex, just your normal PHP string functions

$str = "

yada yada yada
yada
yada yada
yada (bada bada
bada bada

bada) yada yada yada
yada yada
yada yada yada
( yo yo )
";

$s = explode(")",$str,2);
$what_i_want=$s[0];
$m = strpos($what_i_want,"(");  #find where opening brace is
print substr($what_i_want,$m+1); #print from opening brace onwards
ghostdog74