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 dogs 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With