开发者

Delete first instance of string with PHP

How do I delete the first instance of a s开发者_运维问答ubstring in another string with PHP? Thanks.


Something like this may do the trick.

function replaceFirst($input, $search, $replacement){
    $pos = stripos($input, $search);
    if($pos === false){
        return $input;
    }
    else{
        $result = substr_replace($input, $replacement, $pos, strlen($search));
        return $result;
    }
}

$input = "This is a test. This is only a test.";
$search = "test";
echo replaceFirst($input, $search, "replaced!");
// "This is a replaced!. This is only a test."

Sorry for all the edits, had some weird formatting issues.


Try something with the general idea of this:

$search = "boo";
$str = "testtestbootest";
$pos = strpos(strrev($str), strrev($search));
$newstr = substr($str, 0, $pos) . substr($str, $pos + strlen($search));


if your regex skills are up to it use preg_replace, with a limit = 1

mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )

http://php.net/manual/en/function.preg-replace.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜