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


当前回答

你可以用这个:

function str_replace_once($str_pattern, $str_replacement, $string){ 

        if (strpos($string, $str_pattern) !== false){ 
            $occurrence = strpos($string, $str_pattern); 
            return substr_replace($string, $str_replacement, strpos($string, $str_pattern), strlen($str_pattern)); 
        } 

        return $string; 
    } 

从php.net找到这个例子

用法:

$string = "Thiz iz an examplz";
var_dump(str_replace_once('z','Z', $string)); 

输出:

ThiZ iz an examplz

这可能会降低一点性能,但这是最简单的解决方案。

其他回答

可以用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倍)。

不幸的是,我不知道任何PHP函数可以做到这一点。 你可以像这样很容易地自己卷:

function replace_first($find, $replace, $subject) {
    // stolen from the comments at PHP.net/str_replace
    // Splits $subject into an array of 2 items by $find,
    // and then joins the array with $replace
    return implode($replace, explode($find, $subject, 2));
}

最简单的方法是使用正则表达式。

另一种方法是用strpos()找到字符串的位置,然后用substr_replace()

但我真的会选择RegExp。

编辑:两个答案都已更新,现在是正确的。我将把答案留下,因为函数时间仍然是有用的。

“僵尸”和“太多php”的答案很不幸是不正确的。这是对僵尸发布的答案的修正(因为我没有足够的声誉来发表评论):

$pos = strpos($haystack,$needle);
if ($pos !== false) {
    $newstring = substr_replace($haystack,$replace,$pos,strlen($needle));
}

注意strlen($needle),而不是strlen($replace)。Zombat的例子只有在针头和替代物长度相同的情况下才能正确工作。

下面是与PHP自己的str_replace具有相同签名的函数中的相同函数:

function str_replace_first($search, $replace, $subject) {
    $pos = strpos($subject, $search);
    if ($pos !== false) {
        return substr_replace($subject, $replace, $pos, strlen($search));
    }
    return $subject;
}

这是修改后的“too much php”的答案:

implode($replace, explode($search, $subject, 2));

注意最后的2而不是1。或函数格式:

function str_replace_first($search, $replace, $subject) {
    return implode($replace, explode($search, $subject, 2));
}

我对这两个函数进行了计时,当没有找到匹配时,第一个函数的速度是原来的两倍。当找到匹配时,它们的速度是一样的。

$string = 'this is my world, not my world';
$find = 'world';
$replace = 'farm';
$result = preg_replace("/$find/",$replace,$string,1);
echo $result;