-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 ?

2
  • Possible duplicate of PHP str_replace() with a limit param? Commented May 10, 2017 at 2: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. Commented May 10, 2017 at 3:47

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Oh best ans ^_^
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".

2 Comments

not work , i want output hello i _ animal _ dog and and love tree how can i do ?
@mongkontiya Sorry my mistake, I have fixed my method. I think it is actually simpler than my first method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.