我有一个SQL字符串,我需要从主要的' FROM'中获取表名。值。我需要找到最后一个' FROM'可能会或可能不会有其他约束的事件。以下是字符串的几种显示方式:
$input = "SELECT title, (SELECT name FROM Contact WHERE name = 'foo') as name FROM Account WHERE title = 'president'";
$input = "SELECT title, (SELECT name FROM Contact WHERE name = 'foo') as name FROM Account LIMIT 1";
$input = "SELECT title, (SELECT name FROM Contact WHERE name = 'foo') as name FROM Account OFFSET 3";
$input = "SELECT title, (SELECT name FROM Contact WHERE name = 'foo') as name FROM Account ANYTHING_HERE_REALLY";
$input = "SELECT title, (SELECT name FROM Contact WHERE name = 'foo') as name FROM Account";
所有人的预期输出是:帐户
从搜索论坛到任何游戏,这是我要去的方向,但我知道它不正确。
preg_match('/.*FROM\s([^]]+)\sWHERE/', $input, $output);
答案 0 :(得分:0)
首先,使用正则表达式来级联内容(级联)查询是不好的做法。但是我们走了......
简单地匹配FROM
之后的非空格序列。
注意:由于.*
的Kleene星的贪婪,它肯定会寻找最新的匹配。您的模式实际上旨在通过期望WHERE
子句来过度指定问题。
preg_match('/.*FROM\s+(\S+)/', $input, $output);
示例(使用给定的示例和交互式php -a
):
$ php -a
php > $input = "SELECT title, (SELECT name FROM Contact WHERE name = 'foo') as name FROM Account WHERE title = 'president'";
php > preg_match('/.*FROM\s+(\S+)/', $input, $output);var_dump($output);
array(2) {
[0]=>
string(80) "SELECT title, (SELECT name FROM Contact WHERE name = 'foo') as name FROM Account"
[1]=>
string(7) "Account"
}
php > $input = "SELECT title, (SELECT name FROM Contact WHERE name = 'foo') as name FROM Account LIMIT 1";
php > preg_match('/.*FROM\s+(\S+)/', $input, $output);var_dump($output);
array(2) {
[0]=>
string(80) "SELECT title, (SELECT name FROM Contact WHERE name = 'foo') as name FROM Account"
[1]=>
string(7) "Account"
}
php > $input = "SELECT title, (SELECT name FROM Contact WHERE name = 'foo') as name FROM Account OFFSET 3";
php > preg_match('/.*FROM\s+(\S+)/', $input, $output);var_dump($output);
array(2) {
[0]=>
string(80) "SELECT title, (SELECT name FROM Contact WHERE name = 'foo') as name FROM Account"
[1]=>
string(7) "Account"
}
php > $input = "SELECT title, (SELECT name FROM Contact WHERE name = 'foo') as name FROM Account ANYTHING_HERE_REALLY";
php > preg_match('/.*FROM\s+(\S+)/', $input, $output);var_dump($output);
array(2) {
[0]=>
string(80) "SELECT title, (SELECT name FROM Contact WHERE name = 'foo') as name FROM Account"
[1]=>
string(7) "Account"
}
php > $input = "SELECT title, (SELECT name FROM Contact WHERE name = 'foo') as name FROM Account";
php > preg_match('/.*FROM\s+(\S+)/', $input, $output);var_dump($output);
array(2) {
[0]=>
string(80) "SELECT title, (SELECT name FROM Contact WHERE name = 'foo') as name FROM Account"
[1]=>
string(7) "Account"
}
答案 1 :(得分:0)
这应该适合你:
preg_match_all('/FROM\s?(\S+)/', $input, $output);
$输出:
Array
(
[0] => Array
(
[0] => FROM Contact
[1] => FROM Account
)
[1] => Array
(
[0] => Contact
[1] => Account
)
)