douwen4401 2009-01-17 20: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 18: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条)

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊