像 SQL by preg_match 那样分解一个字符串
explode a string like in SQL by preg_match
我想像 SQL
那样分解字符串
这是我的代码:
<?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"];
输出将是:
onlineid
onlinelist
online_user_name=6565
htrdh
1
效果很好...
但是,如果我删除 order by
或 limit
它不起作用。
如果 where
、order by
或 limit
存在于 $subject
中,则必须输入值
您的 ?
没有包含空格。
不正确:... (ORDER BY ...)? (LIMIT ...)?
正确:...( ORDER BY ...)?( LIMIT ...)?
https://www.regex101.com/r/mE8qK5/1
我还建议您将 ?
添加到 .+
子模式中,这样它就不会贪婪地(惰性)匹配
What do lazy and greedy mean in the context of regular expressions?
正则表达式很棘手,除非您了解它的各个方面,否则您应该始终小心使用它。
我还建议使用 /i 不区分大小写
https://www.regex101.com/r/hM9aC7/1
/^select\s+(?<columns>.*?)\s+from\s+(.*?)?((where\s+(?<where>.*?))?(order by\s+(?<order>.*?))?(limit\s+(?<limit>(.*?)))?);/i
我想像 SQL
那样分解字符串这是我的代码:
<?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"];
输出将是:
onlineid
onlinelist
online_user_name=6565
htrdh
1
效果很好...
但是,如果我删除 order by
或 limit
它不起作用。
如果 where
、order by
或 limit
存在于 $subject
中,则必须输入值
您的 ?
没有包含空格。
不正确:... (ORDER BY ...)? (LIMIT ...)?
正确:...( ORDER BY ...)?( LIMIT ...)?
https://www.regex101.com/r/mE8qK5/1
我还建议您将 ?
添加到 .+
子模式中,这样它就不会贪婪地(惰性)匹配
What do lazy and greedy mean in the context of regular expressions?
正则表达式很棘手,除非您了解它的各个方面,否则您应该始终小心使用它。 我还建议使用 /i 不区分大小写
https://www.regex101.com/r/hM9aC7/1
/^select\s+(?<columns>.*?)\s+from\s+(.*?)?((where\s+(?<where>.*?))?(order by\s+(?<order>.*?))?(limit\s+(?<limit>(.*?)))?);/i