开发者

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

开发者 https://www.devze.com 2023-02-01 18:02 出处:网络
What would be the best way to to insert characters after the first occurrence of a word or phrase in a given 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

0

精彩评论

暂无评论...
验证码 换一张
取 消