简体   繁体   English

用PHP中的数组元素替换重复字符

[英]Replace repeating character with array elements in PHP

I hope this is blindingly obvious: I'm looking for the fastest way to replace a repeating element in a string with the elements in a given array, eg for SQL queries and parameter replacement. 我希望这是显而易见的:我正在寻找用给定数组中的元素替换字符串中重复元素的最快方法,例如用于SQL查询和参数替换。

$query  = "SELECT * FROM a WHERE b = ? AND c = ?";
$params = array('bee', 'see');

Here I would like to replace the instances of ? 在这里我想替换实例吗? with the corresponding ordered array elements, as so: 具有相应的有序数组元素,如下所示:

SELECT * FROM a WHERE b = 'bee' and c = 'see'

I see that this might be done using preg_replace_callback , but is this the fastest way or am I missing something obvious? 我看到可以使用preg_replace_callback完成此操作,但这是最快的方法还是我遗漏了一些明显的东西?

Edit : I am already using prepared statements which achieves the above. 编辑 :我已经在使用准备好的语句,实现上述目标。 I am looking for a way to get the raw query back to show as part of debug output. 我正在寻找一种方法来获取原始查询以显示为调试输出的一部分。

Are you looking for prepared statements ? 您在寻找准备好的陈述吗?

<?php
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name = ?");
if ($stmt->execute(array($_GET['name']))) {
  while ($row = $stmt->fetch()) {
    print_r($row);
  }
}
?>

Use PDO to do your SQL queries . 使用PDO进行SQL查询 It does parametrized queries, so you don't need to roll your own method. 它执行参数化查询,因此您无需滚动自己的方法。

For a more generic method, see sprintf() (which won't escape data to make it safe, so don't use it for database access). 有关更通用的方法,请参见sprintf() (该方法不会转义数据以确保其安全,因此请勿将其用于数据库访问)。

I would also recommend using PDO as @David Dorward already suggests. 我还将建议使用@David Dorward已经建议的PDO。 Then: 然后:

$stmt = $dbh->prepare('SELECT * FROM a WHERE b = ? AND c = ?');
$stmt->execute(array('bee', 'see'));

Found this years after it was asked. 被问到之后发现了这一年。 For anyone else looking and not satisfied with the other answers. 对于寻找其他答案而不满意的其他人。 This is how I did ended up doing it: 这是我最终做的事情:

echo preg_replace(array_fill(0,count($params),'/\?/'),$params,$query,1);

Note: This is purely for debugging and does no data cleaning. 注意:这纯粹是为了调试,不会清除数据。

This could probably be expanded, if you knew the intended datatype for each parameter, to add in any quotes around values. 如果您知道每个参数的预期数据类型,则可以扩展此值,以在值周围添加任何引号。 These are automatically created when using something like sqlsrv_query($conn,$query,$params); 这些在使用sqlsrv_query($ conn,$ query,$ params)之类的东西时会自动创建;

I once found the following in an inherited codebase, which I thought was a nifty way of doing these kind of substitutions: 我曾经在继承的代码库中找到以下内容,我认为这是进行此类替换的一种巧妙方法:

function do_substitution($query, $params) {
    $params = array_unshift($params, $query);
    $query = call_user_func_array('sprintf', $params);

    return $query;
}

Ofcourse, you are substituting %s, %d, etc. marks this way. 当然,您是用%s,%d等标记这种方式。

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

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