答案 0 :(得分:1)
你没有做错任何事。您的代码按发布方式工作。如你所说,40以下单词的句子工作得很好。在您的评论中,您声明要将句子截断为40 字符。这可能有所帮助。
$inputString = 'This is a sentence, This is a sentence This is a sentence!';
$max = 40;
$min = 3;
$words = preg_match_all('#\w#', $inputString, $m);
if ($words >= $min) {
$result = (strlen($inputString) <= $max) ? ($inputString) :
(substr($inputString, 0, $max));
} else {
$result = 'bad sentence';
}
echo $result;
答案 1 :(得分:0)
您可以使用str_word_count() function。一个例子:
<?php
$str = "Hello fri3nd, you're
looking good today!";
print_r(str_word_count($str, 1));
print_r(str_word_count($str, 2));
print_r(str_word_count($str, 1, 'àáãç3'));
echo str_word_count($str);
?>