Search code examples
phppreg-match

explode a string like in SQL by preg_match


I want to explode a string like in SQL

this is my code:

<?php

$subject = 'select onlineid from onlinelist where online_user_name=6565 order by htrdh limit 1';

preg_match('/^(select|SELECT) (?P<select>(.+)) (from|FROM) (?P<from>(.+)) ((where|WHERE) (?P<where>(.+))) ((order by|ORDER BY) (?P<order>(.+)))? ((limit|LIMIT) (?P<limit>(.+)))?$/', $subject, $matches);

echo @$matches["select"]."<br>".@$matches["from"]."<br>".@$matches["where"]."<br>".@$matches["order"]."<br>".@$matches["limit"];

outPut will be :

onlineid
onlinelist
online_user_name=6565
htrdh
1

workes well... But if I remove order by or limit it does not work.

it must if where, order by or limit exists in $subject put value


Solution

  • Your ? did not include the spaces.

    Incorrect: ... (ORDER BY ...)? (LIMIT ...)?

    Correct: ...( ORDER BY ...)?( LIMIT ...)?

    https://www.regex101.com/r/mE8qK5/1

    I also recommend that you add ? to the .+ subpatterns so that it won't match greedily (lazy)

    What do lazy and greedy mean in the context of regular expressions?