user3205189
user3205189

Reputation:

Regex not capturing properly

Here is a query I just want to build an array of parameters:

$subject = "SELECT * FROM a_table WHERE something='col1=:param1' AND col2=:param2 OR col3=:param3"; 

I tried:

$pattern = "^([\"'])(?:(?=(\\\\?))\\2.)*?\\1^"; 
$subject = preg_replace($pattern, "", $subject); 

and

$pattern = '#[:][a-zA-Z0-9_]+#'; 
preg_match_all($pattern, $subject, $matches); 
print_r($matches);

Unfortunately I got only param2 and param3 as output

I would like my dump to look like this:

Array ( [0] => :param1 [1] => :param2 [2] => :param3 )

Upvotes: 0

Views: 48

Answers (1)

Pedro Lobito
Pedro Lobito

Reputation: 99081

you can simply use this regex =(:\w+)

$query = "SELECT * FROM a_table WHERE something='col1=:param1' AND col2=:param2 OR col3=:param3";

preg_match_all('/=(:\w+)/', $query, $params, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($params[1]); $i++) {

    echo $params[1][$i]."\n";
}

DEMO http://ideone.com/aut6q2

Upvotes: 2

Related Questions