使用 str_replace 使其仅作用于第一个匹配项? [英] Using str_replace so that it only acts on the first match?

查看:33
本文介绍了使用 str_replace 使其仅作用于第一个匹配项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个 str_replace() 版本,它只替换 $subject 中第一次出现的 $search.有没有简单的解决方案,或者我需要一个hacky的解决方案?

I want a version of str_replace() that only replaces the first occurrence of $search in the $subject. Is there an easy solution to this, or do I need a hacky solution?

推荐答案

可以通过 preg_replace 完成:

function str_replace_first($search, $replace, $subject)
{
    $search = '/'.preg_quote($search, '/').'/';
    return preg_replace($search, $replace, $subject, 1);
}

echo str_replace_first('abc', '123', 'abcdef abcdef abcdef'); 
// outputs '123def abcdef abcdef'

神奇之处在于可选的第四个参数 [Limit].来自文档:

The magic is in the optional fourth parameter [Limit]. From the documentation:

[Limit] - 可能的最大值每个模式中的每个模式的替换主题字符串.默认为 -1(无限制).

[Limit] - The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit).


尽管如此,请参阅 zombat 的答案 一种更有效的方法(大约快 3-4 倍).


Though, see zombat's answer for a more efficient method (roughly, 3-4x faster).

这篇关于使用 str_replace 使其仅作用于第一个匹配项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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