1

How do I delete the first instance of a substring in another string with PHP? Thanks.

1

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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));

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.