How do you insert characters after the first occurrence of a word or phrase in a string?
What would be the best way to to insert characters after the first occurrence of a word or phrase in a given string?
e.g.
$var = 'The big brown dog jumped over the fence';
Insert an "s" after dog making it, "The big brown dog开发者_Python百科s jumped over the fence".
Thanks :)
With a combination of strpos
and substr_replace
:
function str_insert($str, $search, $insert) {
$index = strpos($str, $search);
if($index === false) {
return $str;
}
return substr_replace($str, $search.$insert, $index, strlen($search));
}
DEMO
精彩评论