Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

php

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 :)

like image 410
hsatterwhite Avatar asked Nov 26 '25 07:11

hsatterwhite


1 Answers

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

like image 100
Felix Kling Avatar answered Nov 27 '25 21:11

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!