我需要查明字符串中是否有任何冗余的单词。是否有任何函数可以提供结果为true / false。
示例:
$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
谢谢
答案 0 :(得分:1)
您可以使用explode生成包含字符串中所有单词的数组:
$array = explode(" ", $str);
您可以证明数组是否包含与此答案中提供的函数重复的内容: https://stackoverflow.com/a/3145660/5420511
答案 1 :(得分:0)
我认为这就是你要做的事情,这会分裂在标点符号或空格上。如果您需要重复的单词,可以使用注释掉的行:
$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