How do you insert characters after the first occurrence of a word or phrase in a string?

What would be the best way to insert characters after the first occurrence of a word or phrase in a given string?

eg.

$ var = 'A large brown dog jumped over the fence;

Insert "s" after the dog does this: "Big brown dogs jumped over the fence."

Thank:)

+3
source share
1 answer

With a combination of strposand 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

+10
source

Source: https://habr.com/ru/post/1782087/