我有这段代码
$Models = [
'users' => 'm_users',
'products' => 'm_products',
'customers' => 'm_customers'];
$string = "SELECT users as Name,`users`.`family` AS Family, products.id AS PID, `customers`.`id` AD CID FROM users INNER JOIN customers INNER JOIN products WHERE customers.customers = 1 and users.users = 2 and `products`.`id` = 1 and products.name = 'me' ORDER BY customers.id DESC";
$string_1 = "SELECT users FROM users";
foreach ($Models as $alias => $table) {
$string = preg_replace("/(\s|,)`?{$alias}`?/", "$1`{$table}`", $string);
}
我想替换表名,但它不适用于任何sql查询字符串 例如 $ string 和 $ string_1
答案 0 :(得分:1)
以下内容将仅替换选择FROM的表格,而不取代SELECT中的表格引用,即users.some_field
。
$str = 'SELECT users, users.some_field FROM users';
preg_replace("/(?<=FROM\s)(users)/", "m_users", $str);
// SELECT users, users.some_field FROM m_users
编辑:这个应该替换SELECT中的表引用。
$str = 'SELECT users, users.some_field FROM users';
preg_replace("/(?<=FROM\s)(users)|(users(?=\.))/", "m_users", $str);
// SELECT users, m_users.some_field FROM m_users
把它放到你的循环中:
$Models = [
'users' => 'm_users',
'products' => 'm_products',
'customers' => 'm_customers'
];
$string = "SELECT users as Name,`users`.`family` AS Family, products.id AS PID, `customers`.`id` AD CID FROM users INNER JOIN customers INNER JOIN products WHERE customers.customers = 1 and users.users = 2 and `products`.`id` = 1 and products.name = 'me' ORDER BY customers.id DESC";
foreach ($Models as $alias => $table) {
$string = preg_replace("/(?<=FROM\s)({$alias})|({$alias}(?=\.))/", $table, $string);
}