Kowsalya
Kowsalya

Reputation: 33

PHP replace 2nd occurrence of word

I have sentence in my text file like below.

The quick brown fox jumps over the lazy fox.

How do I replace the second occurrence of "fox" with some other word like "dog" in PHP.

The result should be

The quick brown fox jumps over the lazy dog.

'How to replace a nth occurrence in a string', this question is for how to replace (for eg) 2nd character in a string but my question is replace 2nd word in a sentence.

Upvotes: 1

Views: 1113

Answers (1)

Shahmee
Shahmee

Reputation: 299

this function help you to replace last occurrence

echo str_lreplace('fox','dog','The quick brown fox jumps over the lazy fox.');
function str_lreplace($search, $replace, $subject)
{
$pos = strrpos($subject, $search);

if($pos !== false)
{
    $subject = substr_replace($subject, $replace, $pos, strlen($search));
}

return $subject;
}

Upvotes: 2

Related Questions