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
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
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.
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.
<?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.
$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".
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