-1

I have a sql query like below:

select * from tbl_test where id=:id and name=:name

now I want to extract all variables from above string. for this reason I want to use preg_match() function in php. but I don't know how to write that regular experssion.

can anybody help me to solve this problem?

Mohammad
  • 21,175
  • 15
  • 55
  • 84
  • 2
    There are no variables in the query. You want the placeholders? `:\w+` should do it for you I think (https://stackoverflow.com/questions/5809951/pdo-valid-characters-for-placeholders) – user3783243 Nov 29 '18 at 15:17
  • consider :variable in query as a variable. I want to find all :id and :name. –  Nov 29 '18 at 15:24
  • Provided regex should do that..did you try it? – user3783243 Nov 29 '18 at 15:26

1 Answers1

0

Use pattern /(\w+)=(:\w+)/ that match string before and after =

$str = "select * from tbl_test where id=:id and name=:name";
preg_match_all("/(\w+)=(:\w+)/", $str, $m);
print_r($m[2]);

Output

Array
(
    [0] => :id
    [1] => :name
)

Also you can use array_combine() to create key/value array

$arr = array_combine($m[1], $m[2]);
print_r($arr);

Output

Array
(
    [id] => :id
    [name] => :name
)

Check result in demo

Mohammad
  • 21,175
  • 15
  • 55
  • 84