简体   繁体   English

在 PHP 中删除两个或多个字符串文本之间的重复单词

[英]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.谢谢你。

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

使用str_replacemb_str_replace (对于多字节字符串,例如包含非拉丁符号)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM