我想要str_replace()的一个版本,它只替换$subject中第一次出现的$search。有一个简单的解决方案,还是我需要一个hack的解决方案?


当前回答

可以用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]。从文档中可以看到:

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

不过,请参阅zombat的回答以获得更有效的方法(大约快3-4倍)。

其他回答

这个函数很大程度上受到@ renoor回答的启发。 它使函数多字节安全。

function str_replace_limit($search, $replace, $string, $limit)
{
    $i = 0;
    $searchLength = mb_strlen($search);

    while(($pos = mb_strpos($string, $search)) !== false && $i < $limit)
    {
        $string = mb_substr_replace($string, $replace, $pos, $searchLength);
        $i += 1;
    }

    return $string;
}

function mb_substr_replace($string, $replacement, $start, $length = null, $encoding = null)
{
    $string = (array)$string;
    $encoding = is_null($encoding) ? mb_internal_encoding() : $encoding;
    $length = is_null($length) ? mb_strlen($string) - $start : $length;

    $string = array_map(function($str) use ($replacement, $start, $length, $encoding){

        $begin = mb_substr($str, 0, $start, $encoding);
        $end = mb_substr($str, ($start + $length), mb_strlen($str), $encoding);

        return $begin . $replacement . $end;

    }, $string);

    return ( count($string) === 1 ) ? $string[0] : $string;
}

=> CODE已被修订,所以考虑一些太旧的注释

感谢大家帮助我改进这一点 有任何BUG,请与我沟通;我马上就去做

那么,让我们开始:

将第一个o替换为ea,例如:

$s='I love you';
$s=str_replace_first('o','ea',$s);
echo $s;

//output: I leave you

功能:

function str_replace_first($this,$that,$s)
{
    $w=strpos($s,$this);
    if($w===false)return $s;
    return substr($s,0,$w).$that.substr($s,$w+strlen($this));
}

我创建了这个小函数,用limit替换字符串上的字符串(区分大小写),而不需要Regexp。它工作得很好。

function str_replace_limit($search, $replace, $string, $limit = 1) {
    $pos = strpos($string, $search);

    if ($pos === false) {
        return $string;
    }

    $searchLen = strlen($search);

    for ($i = 0; $i < $limit; $i++) {
        $string = substr_replace($string, $replace, $pos, $searchLen);

        $pos = strpos($string, $search);

        if ($pos === false) {
            break;
        }
    }

    return $string;
}

使用示例:

$search  = 'foo';
$replace = 'bar';
$string  = 'foo wizard makes foo brew for evil foo and jack';
$limit   = 2;

$replaced = str_replace_limit($search, $replace, $string, $limit);

echo $replaced;
// bar wizard makes bar brew for evil foo and jack
$string = 'this is my world, not my world';
$find = 'world';
$replace = 'farm';
$result = preg_replace("/$find/",$replace,$string,1);
echo $result;

我会用孕妇代替。它有一个LIMIT参数,你可以将它设置为1

preg_replace (regex, subst, string, limit) // default is -1