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"...
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
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With