我需要一个简单而快速的解决方案来替换字符串中的第n个匹配项(占位符)。
例如,sql查询中的第n个问号应替换为提供的值。
$subject = "SELECT uid FROM users WHERE uid = ? or username = ?";
所以,我需要像str_replace_nth($seach, $replace, $subject, $nth)
这样的函数,对于第二个问号它应该被称为str_replace_nth("?", $username, $subject, 2);
有什么想法吗?
P.S。请不要建议我使用PDO,因为我正在FDO (Facebook Data Object)使用类似于PDO的接口的库,但是对于FQL。
重要通知!我发现这种方法很糟糕,因为在第一次更换后,修改了查询并丢失了索引。 (当你在深夜编程时出现不好的方法:()所以,正如@GolezTrol在评论中提到的那样,最好立刻替换所有。
答案 0 :(得分:13)
以下是您要求的功能:
$subject = "SELECT uid FROM users WHERE uid = ? or username = ?";
function str_replace_nth($search, $replace, $subject, $nth)
{
$found = preg_match_all('/'.preg_quote($search).'/', $subject, $matches, PREG_OFFSET_CAPTURE);
if (false !== $found && $found > $nth) {
return substr_replace($subject, $replace, $matches[0][$nth][1], strlen($search));
}
return $subject;
}
echo str_replace_nth('?', 'username', $subject, 1);
注意:$nth
是基于零的索引!
但我建议使用以下内容替换占位符:
$subject = "SELECT uid FROM users WHERE uid = ? or username = ?";
$args = array('1', 'steve');
echo vsprintf(str_replace('?', '%s', $subject), $args);
答案 1 :(得分:6)
不使用问号,为什么不使用这样的标记:
$subject = "SELECT uid FROM users WHERE uid = :uid or username = :username";
$parameters = array(
':uid' => 42,
':username' => 'John',
);
$subject = str_replace(array_keys($parameters), $parameters, $subject);
答案 2 :(得分:0)
未完成输入参数验证
function str_replace_nth($search, $replace, $subject, $nth){
$match_arr = explode($search,$subject);
$match_arr = array_filter($match_arr);
foreach($match_arr as $key=>$val){
if($key == $nth-1){ // array index start with Zero
$match_arr[$key] .= $replace;
}else{
$match_arr[$key] .= '?';
}
}
return implode('',$match_arr);
}
答案 3 :(得分:0)
你的解决方案都不适合我,所以我做到了:
$sql1 = "SELECT * FROM allegro_user WHERE User_Emp_Nb = ? AND User_Activ_status = ?";
$sql2 = "SELECT * FROM allegro_user WHERE User_Emp_Nb = :emp_nb AND User_Activ_status = :activ";
function prepare_query($sql, $args) {
foreach ($args as $key => $value) {
if (is_numeric($key)) {
$sql = preg_replace('/\?/', "'" . $value . "'", $sql, 1);
} else {
$sql = str_replace($key, "'" . $value . "'", $sql);
}
}
return $sql;
}
tab($sql1);
$sql = prepare_query($sql1, array('0216313', 'A'));
tab($sql1);
tab($sql2);
$sql = prepare_query($sql2, array(':emp_nb' => '0216313', ':activ' => 'A'));
tab($sql2);
tab()只是我用于打印的功能:
echo '<pre>';
print_r($tab);
echo '</pre>';