如果数字与预期不同,如何计算可变词并以不同的样式回显
How to count variable words and echo it with different styles if number is other than expected
假设我有一个包含随机单词数的变量。例如,如果 variable 有 2 个单词,则它应该是 echo
和一种样式。如果有 3 个字,那么 echo
它与其他样式...等...
$mywords = "some sentence goes here";
if ... { // what to do next?
echo '<span style="style1">$mywords</span>';
}
elseif ... // ?
关于如何实现这一点的想法?
使用str_word_count()
:
$mywords = "some sentence goes here";
$countWords = str_word_count($mywords);
if ($countWords === 3) {
} elseif($countWords === 4) {
//This gets executed
} else {
}
您可以使用 explode 根据分隔符(在您的情况下为 space)将字符串转换为数组,然后计算数组中元素的数量。
示例:
$test = explode(" ", $inputString);
echo count($test);
假设我有一个包含随机单词数的变量。例如,如果 variable 有 2 个单词,则它应该是 echo
和一种样式。如果有 3 个字,那么 echo
它与其他样式...等...
$mywords = "some sentence goes here";
if ... { // what to do next?
echo '<span style="style1">$mywords</span>';
}
elseif ... // ?
关于如何实现这一点的想法?
使用str_word_count()
:
$mywords = "some sentence goes here";
$countWords = str_word_count($mywords);
if ($countWords === 3) {
} elseif($countWords === 4) {
//This gets executed
} else {
}
您可以使用 explode 根据分隔符(在您的情况下为 space)将字符串转换为数组,然后计算数组中元素的数量。
示例:
$test = explode(" ", $inputString);
echo count($test);