0

I got a string that sometime will have instance of

This is Hello World Hello Thanks

Notice that Hello was repeat twice, I would like to replace the first "occurence" of Hello and Make it as

This is World Hello Thanks

Is there a way I can check if there is a word is repeat twice, and to remove the first occurence and get the final string.

The only I could think of is using explode, and get each word by delimiter "white space".

And then I not sure how to proceed on like counting occurance and removing the repeated word.

Thanks for helping

Baoky chen
  • 183
  • 7
  • 15

1 Answers1

0

As per this question: Using str_replace so that it only acts on the first match?

$str = 'abcdef abcdef abcdef';
// pattern, replacement, string, limit
echo preg_replace('/abc/', '123', $str, 1); // outputs '123def abcdef abcdef'

So you could use:

preg_replace('#Hello#', '', $input, 1)

To count the amount of times if Hello appears, see http://php.net/manual/en/function.substr-count.php

$count = substr_count($input, 'Hello');

Community
  • 1
  • 1
user3791372
  • 4,445
  • 6
  • 44
  • 78
  • Wrong. `$count` is not for that. `str_replace` will replace all occurrences, you can't specify how many you want removed. `$count` parameter does this : `If passed, this will be set to the number of replacements performed. ` – Hanky Panky Oct 04 '15 at 16:07