douwen4401 2009-01-17 12:31
浏览 44
已采纳

PHP / RegEx - 用于预先添加表名的逻辑

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');

INPUT:

id > 1 AND (name = 'Hello' OR label IN ('World', 'Planet name AND label')) AND (related_value > 1 AND related_value < 50)

OUTPUT:

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)

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?

  • 写回答

3条回答 默认 最新

  • douliangli6407 2009-10-09 10:09
    关注

    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'
    );
    

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部