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
2010-07-12 02:41:59
Bur doesn't that remove all instances and not just the first?
usertest
2010-07-12 02:43:00
Yes. It's close, but not quite. You can get exactly what you want by combining substr() and strpos().
Kalium
2010-07-12 02:45:12
Good call. http://help4php.wordpress.com/2007/11/26/substring-substr-and-stringposition-strpos/ is a tutorial
Mike
2010-07-12 02:47:23
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 ]] )
bumperbox
2010-07-12 02:45:47
+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
2010-07-12 02:49:53
+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
2010-07-12 03:06:26