preg_match contents in parentheses

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
gth759k
Forum Commoner
Posts: 76
Joined: Mon Jun 15, 2009 3:04 am

preg_match contents in parentheses

Post 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.
mayanktalwar1988
Forum Contributor
Posts: 133
Joined: Wed Jul 08, 2009 2:44 am

Re: preg_match contents in parentheses

Post 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.
mayanktalwar1988
Forum Contributor
Posts: 133
Joined: Wed Jul 08, 2009 2:44 am

Re: preg_match contents in parentheses

Post 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.
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: preg_match contents in parentheses

Post 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]);
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
Post Reply