我需要找出字符串中是否有多余的单词。是否有任何函数可以为我提供真/假结果。
例:
$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);
然后你可以证明数组是否包含重复项,并具有以下答案中提供的函数:https://stackoverflow.com/a/3145660/5420511
我认为
这就是您要做的,这会在标点符号或空格上拆分。如果需要重复的单词,可以使用注释掉的行:
$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';
// }
//}
}
引用:
http://php.net/manual/en/function.array-count-values.php
http://php.net/manual/en/function.max.php
http://php.net/manual/en/function.preg-split.php
正则表达式演示:https://regex101.com/r/iH0eA6/1