Page 1 of 1

preg_match contents in parentheses

Posted: Tue Jun 08, 2010 8:13 pm
by gth759k
I've never fully understood regular expressions, which is why I can't seem to figure this out. I'm trying to match the contents from various parentheses in a paragraph to an array. Like this:

$paragraph = "Once upon a time a (horrible) programmer felt that regular expressions were (not) very helpful."
$parentheses = magicfunction($paragraph);
var_dump($parentheses);

With output like this:

array(2) { [0]=> string(8) "horrible" [1]=> string(3) "not" }

Any help would be appreciated. Thanks.

Re: preg_match contents in parentheses

Posted: Tue Jun 08, 2010 10:54 pm
by mayanktalwar1988
here is you regular expression code

Code: Select all

<?php
$str="Once upon a time a (horrible) programmer felt that regular expressions were (not) very helpful";
preg_match_all("/(\()(.+?)(\))/",$str,$outputarray);
print_r($outputarray[2]);
?>
it outputs for the above given string is
Array ( [0] => horrible [1] => not )

the output is contained in outputarray[2]

if you want to start learning regular regular expression i recommend you "sams teach yourself regular expression in ten miunutes" ..to start.

Re: preg_match contents in parentheses

Posted: Tue Jun 08, 2010 10:54 pm
by mayanktalwar1988
here is you regular expression code

Code: Select all

<?php
$str="Once upon a time a (horrible) programmer felt that regular expressions were (not) very helpful";
preg_match_all("/(\()(.+?)(\))/",$str,$outputarray);
print_r($outputarray[2]);
?>
it outputs for the above given string is
Array ( [0] => horrible [1] => not )

the output is contained in outputarray[2]

if you want to start learning regular regular expression i recommend you "sams teach yourself regular expression in ten miunutes" ..to start.

Re: preg_match contents in parentheses

Posted: Wed Jun 09, 2010 9:48 am
by AbraCadaver
This will do it as well:

Code: Select all

$str = "Once upon a time a (horrible) programmer felt that regular expressions were (not) very helpful";
preg_match_all("/\(([^\)]+)\)/", $str, $outputarray);
print_r($outputarray[1]);