如何替换字符串中的第n个匹配项 [英] How to replace a nth occurrence in a string

查看:215
本文介绍了如何替换字符串中的第n个匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个简单快速的解决方案来替换字符串中的第n个出现的位置(占位符).

I need a simple and fast solution to replace nth occurrence (placeholder) in a string.

例如,应将sql查询中的第n个问号替换为提供的值.

For example, nth question mark in sql query should be replaced with a provided value.

$subject = "SELECT uid FROM users WHERE uid = ? or username = ?";

所以,我需要像str_replace_nth($seach, $replace, $subject, $nth)这样的函数,对于第二个问号,应将其称为str_replace_nth("?", $username, $subject, 2);

So, i need function like str_replace_nth($seach, $replace, $subject, $nth) and for second question mark it should be called as str_replace_nth("?", $username, $subject, 2);

有什么想法吗?

P.S.请不要建议我使用PDO,因为我正在使用 FDO(Facebook数据对象)具有类似于PDO的接口的库,但用于FQL.

P.S. Please, don't suggest me to use PDO, because I'm working on FDO (Facebook Data Object) a library with an interface similar to PDO, but for FQL.

重要提示!!我发现这种方法不好,因为在第一次替换后,查询被修改,索引丢失. (当您在深夜编程时,错误的方法会出现:()因此,正如@GolezTrol在评论中提到的,最好一次全部替换掉​​.

Important notice! I've figured out that this approach is bad because after first replacement the query is modified and indexes are lost. (Bad approaches come when you're programming late at night :() So, as @GolezTrol mention in comment, it's better to replace all at once.

推荐答案

以下是您要求的功能:

$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是从零开始的索引!

Note: $nth is a zero based index!

但是我建议使用类似以下的内容替换占位符:

But I'll recommend to use something like the following to replace the placeholders:

$subject = "SELECT uid FROM users WHERE uid = ? or username = ?";

$args = array('1', 'steve');
echo vsprintf(str_replace('?', '%s', $subject), $args);

这篇关于如何替换字符串中的第n个匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆