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

查看:120
本文介绍了使用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($from, $to, $content)
{
    $from = '/'.preg_quote($from, '/').'/';

    return preg_replace($from, $to, $content, 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).


尽管如此,请参见


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

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

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