如何检查字符串是多字句还是单个字?
我尝试通过空格分割,所以如果它是一个单词,则数组中只有一个单词,如果有更多,那么它们都将在数组中。
但是,当我尝试按空格分割并运行该数组时,我没有输出。
以下是代码:
$input = "the quick brown fox jumped over the lazy dog";
$sentence = explode(" ", $input);
foreach($sentence as $item){
echo $item;
}
上面没有给我输出。
所以,我有两个问题:
答案 0 :(得分:4)
没有在此或hek2mgl的解决方案之间运行指标,但这应该更快:
if (stripos($input, ' ') !== false) { echo 'ZOMG I HAS WORDS'; }
此外,正如评论中所述,您发布的代码按预期工作。
答案 1 :(得分:2)
作为参考,还有str_word_count($string)
,它还提供字符串中的单词数。
答案 2 :(得分:1)
如何检测字符串是否由if语句中的多个单词组成?
if(count(explode(' ', $str)) > 0) { echo 'sentence'; }
为什么上面的代码不能将句子分成带有单词?
的数组
代码应该有效。我得到了(在为回声添加换行符之后):
the
quick
brown
fox
jumped
over
the
lazy
dog
答案 3 :(得分:0)
您的代码应该正常工作,以检查您是否需要检查多个单词,如下所示
$input = "the quick brown fox jumped over the lazy dog";
$sentence = explode(" ", $input);
echo "<pre>";
var_dump($sentence);
echo "</pre>";
if(count($sentence)){
echo "we have more than one word!";
}
答案 4 :(得分:-1)
要检查是否有空格,您可以使用正则表达式:
$spaces = preg_match('/ /',$input);
这应该返回1或0,具体取决于是否有空格。
if( $spaces == 1 )
// there is more than one word
else
// there is only one word with no spaces
除此之外,您的代码看起来没有错误。
答案 5 :(得分:-1)
下面是一些假代码:
String input = "The quick brown fox jumped over the lazy dog"
Array[] words = String.split(input,' ');
if(words.length > 1)
print " more than 1 word"
else
print "1 word"