如何替换字符串中的第n个匹配项

编程入门 行业动态 更新时间:2024-10-28 16:18:29
本文介绍了如何替换字符串中的第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个匹配项

本文发布于:2023-11-01 17:26:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1549946.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!