Skip to content
Advertisement

Remove duplicated words between two and more string texts in PHP

Words:

$word_1 = "My Subject Test Words Are Here"
$word_2 = "My Subject Different Word is there"
$word_3 = "My Subject Other Word is there"

In this words i want to remove “My Subject”, the end of the day words should replaced like:

$word_1 = "Test Words Are Here"
$word_2 = "Different Word is there"
$word_3 = "Other Word is there"

My subject can be dynamically change it can be three word or four word.

Is it possible to remove first duplicated words from string?

Thank you.

Advertisement

Answer

You could find the duplicate words by splitting it by space and convert into array then you can find the first match duplicate words

$words = [
  "My Subject Test Words Are Here",
  "My Subject Different Word is there",
  "My Subject Other Word is there"
];

$wordSplits = array_map(function($word) {
  return preg_split('/s+/', $word, -1, PREG_SPLIT_NO_EMPTY);
},$words);

$removeDuplicates = array_map(function($word) use($wordSplits) {
  return trim(str_replace(
    array_intersect(array_shift($wordSplits),...$wordSplits),
    '',
    $word
  ));
},$words);

var_dump($removeDuplicates);

Results:

array(3) {
  [0]=>
  string(19) "Test Words Are Here"
  [1]=>
  string(23) "Different Word is there"
  [2]=>
  string(13) "Other Word is there"
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement