PHP/RegEx-表名前面的逻辑 [英] PHP/RegEx - Logic for prepending table names
问题描述
因此,我正在尝试构建一个脚本,该脚本以适当的表前缀自动为有效的列名加上前缀(例如"t."或"r.")
So I'm trying to build a script that automagically prepends valid column names with its appropriate table prefix (e.g. "t." or "r.")
$t_columns = array('id', 'name', 'label');
$r_columns = array('related_value');
输入:
id > 1 AND (name = 'Hello' OR label IN ('World', 'Planet name AND label')) AND (related_value > 1 AND related_value < 50)
输出:
t.id > 1 AND (t.name = 'Hello' OR t.label IN ('World', 'Planet name AND label')) AND (r.related_value > 1 AND r.related_value < 50)
请注意,您不能执行常规的 str_replace .什么是最简单的代码(我猜是 preg_replace ),以确保所有表名都正确地加上了前缀?
Notice how you can't do a normal str_replace. What would be the simplest code (I'm guessing preg_replace) to ensure that all table names are properly prepended?
推荐答案
这可以通过多种方式完成,也可以使用正则表达式.我个人将使用数组方法.首先,我将以这种方式定义修改表:
This can be done in a lot of ways, and also using regex. I'd personally use an array approach. First of all, I'd define the mangling table this way:
$table = array(
'id' => 't.id',
'name' => 't.name',
'label' => 't.label',
'related_value' => 'r.related_value'
);
这将简化str_replace()调用:
This will make a lot easier the str_replace() call:
function mangling(&$v, $k, $table)
{
if (($k & 1) == 0)
$v = str_replace(array_keys($table), array_values($table), $v);
}
$spans = explode("'", ' ' . $input);
array_walk($spans, 'mangling', $table);
$output = implode("'", $spans);
这篇关于PHP/RegEx-表名前面的逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!