簡體   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