-2

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 ?

  • Possible duplicate of [PHP str\_replace() with a limit param?](http://stackoverflow.com/questions/8510223/php-str-replace-with-a-limit-param) – Rulisp May 10 '17 at 02:33
  • @Rulisp no limit param on str_replace(), there is a count param, but that allows you to pass a variable in as a pointer in order to get the number of instances of the string that were replaced. It doesn't actually allow you to limit the number of instances to be replaced. – Dave May 10 '17 at 03:47

2 Answers2

0

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".

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
0

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

Thaiseer
  • 92
  • 7