tags:

views:

52

answers:

4

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

A: 

// Provides: You should eat pizza, beer, and ice cream every day
$phrase = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables", "fiber"); $yummy = array("pizza", "beer", "ice cream");

$newphrase = str_replace($healthy, $yummy, $phrase);

Source: http://php.net/manual/en/function.str-replace.php

Google is a programmer's best friend.

Mike
Bur doesn't that remove all instances and not just the first?
usertest
Yes. It's close, but not quite. You can get exactly what you want by combining substr() and strpos().
Kalium
Good call. http://help4php.wordpress.com/2007/11/26/substring-substr-and-stringposition-strpos/ is a tutorial
Mike
A: 

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

bumperbox
+1  A: 

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));
Graphain
+1  A: 

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.

Greg W