Skip to content
Advertisement

Extract Parameters from pdo query

I have this query using pdo:

SELECT * FROM users WHERE name LIKE :name AND age > :age1 AND age < :age2

how can I extract the parameters from this query with a regular expression in order to get an array similar to:

$arr[0] => name,
$arr[1] => age1,
$arr[2] => age2

Advertisement

Answer

Try this on for size..

(:[^s]*)s?

Here is a demo to this REGEX in action using regexr.com

http://regexr.com/39gnv

And here is a demo in PHP

test.php

$query="Select * from users where name like :name and age > :age1 and age < :age2";
preg_match_all('/(:[^s]*)s?/',$query,$matches);
print_r($matches);

Output of php test.php

Array

    (
        [0] => Array
            (
                [0] => :name
                [1] => :age1
                [2] => :age2
            )

        [1] => Array
            (
                [0] => :name
                [1] => :age1
                [2] => :age2
            )

    )
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement