如何替换PHP只有第一个和第二个单词而不是替换第三个单词?

How to replace PHP only first and second word and not replace third word ?

I have

$test = "hello i love animal love dog and and love tree";

I want to replace fisrt and secode word love to underscore and not replace third word love like this.

hello i _ animal _ dog and and love tree

Then i use this code

$test = str_replace('love', '_', $test);
echo $test;

But result will be

hello i _ animal _ dog and and _ tree

How can i do for replace only first and second word and not replace third word ?

I think this is the result you are looking for:

$subject = "hello i love animal love dog and and love tree";
$search = "love";
$replace = "_";

$pos = strrpos($subject, $search);

$first_subject = str_replace($search, $replace, substr($subject, 0, $pos));
$subject = $first_subject . substr($subject, $pos, strlen($subject));

echo $subject;

Demo here

Here is a regex-free way:

Code (Demo):

$test = "hello i love animal love dog and and love tree";
$test=substr_replace($test,"_",strpos($test,"love"),4);
$test=substr_replace($test,"_",strpos($test,"love"),4);
echo $test;

Output:

hello i _ animal _ dog and and love tree

This method is simple because it does the same method twice -- each time it removes "love at first sight".