使用 Regex [PHP] 拆分 SQL 列名称以及它们的别名(如果有的话)
Splitting SQL column name and if any from their aliases using Regex [PHP]
我想使用 Regex 将列名(如果有)与其别名分开。正如我在下面提到的,我创建了一个表达式,但没有引号它就不起作用。
谢谢!
(?<nameFull> #nameRegex
(?<name>[^"'`]+) #name
(?<nameQoute>["'`]+)? #name Qoute
)
(?<aliasFull> #aliasRegex
\s+ #before Alias WhiteSpace
(?<AS>AS\s+)? #AS Is match or Not match
(?<aliasQoute>["'`])? #alias Qoute
(?<alias>[^"'`]+) #alias
)?
你也可以看到我用this link做的测试。
这是符合您需要的正则表达式:
^\W?(?<table>[\w-]+\.)?(?<name>[\w-]+)\W?(\W+as\W+)?(?<alias>[\w-]+)?\W?$
Test this regular expression online
PHP 片段
$re = "/^\W?(?<table>[\w-]+\.)?(?<name>[\w-]+)\W?(\W+as\W+)?(?<alias>[\w-]+)?\W?$/i";
$array = [
"columnam-e as myalias",
"table.columnam-e as myalias",
'"column" AS "mycolumn"',
"'column' AS 'mycolumn'",
"'table.column' AS 'mycolumn'",
"`column` AS `mycolumn`",
"columnam-e mycolumn",
"colunmanesingle"
];
foreach ($array as $i => $value) {
preg_match($re, $value, $matches);
$name = $matches['name'];
$table = NULL;
$alias = NULL;
if(array_key_exists('table', $matches)) {
$table = $matches['table'];
}
if(array_key_exists('alias', $matches)) {
$alias = $matches['alias'];
}
printf("%s\r=> table: %s, name: %s, alias: %s\r\r", $value, $table, $name, $alias);
}
我想使用 Regex 将列名(如果有)与其别名分开。正如我在下面提到的,我创建了一个表达式,但没有引号它就不起作用。
谢谢!
(?<nameFull> #nameRegex
(?<name>[^"'`]+) #name
(?<nameQoute>["'`]+)? #name Qoute
)
(?<aliasFull> #aliasRegex
\s+ #before Alias WhiteSpace
(?<AS>AS\s+)? #AS Is match or Not match
(?<aliasQoute>["'`])? #alias Qoute
(?<alias>[^"'`]+) #alias
)?
你也可以看到我用this link做的测试。
这是符合您需要的正则表达式:
^\W?(?<table>[\w-]+\.)?(?<name>[\w-]+)\W?(\W+as\W+)?(?<alias>[\w-]+)?\W?$
Test this regular expression online
PHP 片段
$re = "/^\W?(?<table>[\w-]+\.)?(?<name>[\w-]+)\W?(\W+as\W+)?(?<alias>[\w-]+)?\W?$/i";
$array = [
"columnam-e as myalias",
"table.columnam-e as myalias",
'"column" AS "mycolumn"',
"'column' AS 'mycolumn'",
"'table.column' AS 'mycolumn'",
"`column` AS `mycolumn`",
"columnam-e mycolumn",
"colunmanesingle"
];
foreach ($array as $i => $value) {
preg_match($re, $value, $matches);
$name = $matches['name'];
$table = NULL;
$alias = NULL;
if(array_key_exists('table', $matches)) {
$table = $matches['table'];
}
if(array_key_exists('alias', $matches)) {
$alias = $matches['alias'];
}
printf("%s\r=> table: %s, name: %s, alias: %s\r\r", $value, $table, $name, $alias);
}