Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php preg_match starts with keyword

Surely an easy problem, but I can't get is solved...

I just want to detect if my sql query is starting with a "select" or anything else. This code seems not to work :

if (preg_match("/^(select)/i", $sql) > 0)
{
// SELECT query
}
else
{
// other query
}

Thanks for your help !

[EDIT] Ok, I have the root cause: I may have spaces, tabs and line returns before the keyword "select"...

like image 411
Réjôme Avatar asked Feb 03 '12 22:02

Réjôme


2 Answers

A regular expression isn't necessary, use stripos

$query = "SELECT * FROM table WHERE field = 1";

if (stripos(trim($query), "SELECT") === 0)
    echo "Query begins with $str";
else
    echo "Query DOES NOT begin with $str";

// Notice: trim() will remove whitespace before and after your $query string.

Ex: http://ideone.com/hLaBq

Alternatively, if you want to stick with preg_match:

if (preg_match("/^select (.*)/i", trim($query)) > 0) {
    //...

Ex: http://ideone.com/fzh2I

like image 101
Josh Avatar answered Oct 06 '22 00:10

Josh


Try:

if (preg_match("/^[[:space:]]*select/i", $sql))

This will match any (or no) white space between the start and the select, so your spaces, tabs, etc. are accounted for.

Update, it may be this on your system:

if (preg_match("/^\s*select/i", $sql))
like image 21
Jonathan M Avatar answered Oct 05 '22 23:10

Jonathan M