devugur
devugur

Reputation: 1499

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.

Upvotes: 0

Views: 90

Answers (2)

Jerson
Jerson

Reputation: 1745

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

Upvotes: 1

Ilia Yatsenko
Ilia Yatsenko

Reputation: 832

Use str_replace or mb_str_replace (for multibyte strings, e.g. containing non latinic symbols).

$result = str_replace('My Subject', '', $originString);

Upvotes: 0

Related Questions