繁体   English   中英

PHP用数组中的字符串替换字符

[英]PHP Replace character with string from an array

对于 mysql 我使用格式:

$sql = "select * from table where area_id = ? and item_id = ?";

然后准备并绑定参数等。如果查询失败并且我记录了 $sql 变量,那么我会得到上面没有那么有用的字符串。 我想要的是带有绑定值的 sql 字符串。据我所知,没有简单的方法可以做到这一点,所以我想我可以这样做:

sql_log(str_replace('?', array($area_id, $item_id), $sql));

要在我的日志中获得类似的信息:

"select * from table where area_id = West and item_id = West" (spot the error!)

所以我知道我的错误是什么。 但它不起作用。 我明白了:

"select * from table where area_id = Array and item_id = Array"

使用preg_replace_callback函数

$sql = "select * from table where area_id = ? and item_id = ?";
$replace = array('area_id', 'item_id');
echo preg_replace_callback('/\?/', function($x) use(&$replace) { return array_shift($replace);}, $sql);
// select * from table where area_id = area_id and item_id = item_id

不幸的是, mysqli没有一个很好的方法来获取查询。 您可以使用一种方法来替换您的参数:

function populateSql ( string $sql, array $params ) : string {
    foreach($params as $value)
        $sql = preg_replace ( '[\?]' , "'" . $value . "'" , $sql, 1 );
    return $sql;
}

试试这个:

sprintf('select * from table where area_id = %s and item_id = %s', $area_id, $item_id);

或者

sprintf('select * from table where area_id = "%s" and item_id = "%s"', $area_id, $item_id);

如果数据库中的字段是整数,则必须将 %s 替换为 %d 并且不要使用引号

Laravel 有一个漂亮的帮手。

/**
  * Replace a given value in the string sequentially with an array.
  *
  * @param  string  $search
  * @param  array   $replace
  * @param  string  $subject
  * @return string
  */
function replaceArray($search, array $replace, $subject)
{
    $segments = explode($search, $subject);

    $result = array_shift($segments);

    foreach ($segments as $segment) {
        $result .= (array_shift($replace) ?? $search).$segment;
    }

    return $result;
}

$sql = 'SELECT * FROM tbl_name WHERE col_b = ? AND col_b = ?';

$bindings = [
  'col_a' => 'value_a',
  'col_b' => 'value_b',
];

echo replaceArray('?', $bindings, $sql);

// SELECT * FROM tbl_name WHERE col_b = value_a AND col_b = value_b

来源: Str::replaceArray()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM