Jump to content

[SOLVED] preg_match() to find text in the brackets ()


ted_chou12

Recommended Posts

Perhaps

 

preg_match('#\([^)]+\)#', $string);

 

?

 

In your version, you have a star after \( which means zero or more times.. so the opening parenthesis is not required, then match a single character [matched by the dot_match_all wildcard (which is optional because of the ?)] followed by the closing \).. so as you can see, this is not quite what you are looking for.

 

What I have done is look for (, then anything that is not a ), one or more times, followed by ).

It appears my crystal ball is broken and in the shop... so without knowing what the value of $r[$i] is, it's kind of hard to tell, no?

(and unless you know for sure there is going to be (...) in your string, you might want to encase the preg_match in an if statement, in case the pattern doesn't find a match..that way, you have something to fallback on...)

 

Example:

if(preg_match('#\([^)]+\)#', $r[$i], $cont)){
echo $cont[0];
} else {
// do somthing else...
}

sorry, its my bad  ;D, $r[$i] is this:

CREATE TABLE `menu` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `label` varchar(5) NOT NULL,
  `name` varchar(100) NOT NULL,
  `type` int(2) NOT NULL,
  `price` float NOT NULL,
  `availability` int(1) NOT NULL DEFAULT '0',
  `additional` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=23 DEFAULT CHARSET=latin1 ROW_FORMAT=DYNAMIC;

the thing i am trying to accomplish is to collect all the column names into an array. Ignore the brackets things, i think preg_match for `` would be better than matching the (), sorry for confusing you again  :).

Ted

// obviously, you don't use this heredoc, as I am only using this as an example.. you use your version of $r['$i'] instead.
$r['$i'] = <<<DATA
CREATE TABLE `menu` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `label` varchar(5) NOT NULL,
  `name` varchar(100) NOT NULL,
  `type` int(2) NOT NULL,
  `price` float NOT NULL,
  `availability` int(1) NOT NULL DEFAULT '0',
  `additional` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=23 DEFAULT CHARSET=latin1 ROW_FORMAT=DYNAMIC;
DATA;

preg_match_all('#(?<!\()`([^`]+)`(?!\))#', $r['$i'], $tableNames);
unset($tableNames[1][0]); // get rid of `menu`
foreach($tableNames[1] as $val){
echo $val . '<br />';
}

 

Output:

id
label
name
type
price
availability
additional

 

On a side note, you can have a look at this sticky (to help you with asking regex questions in the future).

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.