如何找出php中字符串中是否有多余的单词?
我需要找出字符串中是否有多余的单词。是否有任何函数可以为我提供正确/错误的结果 例如:如何找出php中字符串中是否有多余的单词?,php,Php,我需要找出字符串中是否有多余的单词。是否有任何函数可以为我提供正确/错误的结果 例如: $str = "Hey! How are you"; $result = redundant($str); echo $result ; //result should be 0 or false 但对于: $str = "Hey! How are are you"; $result = redundant($str); echo $result ; //result should be 1 o
$str = "Hey! How are you";
$result = redundant($str);
echo $result ; //result should be 0 or false
但对于:
$str = "Hey! How are are you";
$result = redundant($str);
echo $result ; //result should be 1 or true
谢谢您可以使用explode生成包含字符串中所有单词的数组:
$array = explode(" ", $str);
您可以使用此答案中提供的函数证明数组是否包含重复项:
我想这就是你想要做的,它在标点符号或空格上分开。如果需要重复的单词,可以使用注释掉的行:
$str = "Hey! How are are you?";
$output = redundant($str);
echo $output;
function redundant($string){
$words = preg_split('/[[:punct:]\s]+/', $string);
if(max(array_count_values($words)) > 1) {
return 1;
} else {
return 0;
}
//foreach(array_count_values($words) as $word => $count) {
// if($count > 1) {
// echo '"' . $word . '" is in the string more than once';
// }
//}
}
参考文献:正则表达式演示:@mkaatman:那是完全不同的事情。。。。在这里,我只需要真/假返回。不是哪个词在重复。希望你能理解。如果任何单词的计数大于1,返回true重复的单词可能不是“多余的”。例如,你怎么知道那是我正在读的?;-)