开发者

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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜