How do I delete the first instance of a substring in another string with PHP? Thanks.
3 Answers
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.
Comments
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 ]] )