例子:
a
aaa
aaaaa
aaa
aa
如果给定长度为 3,那么它应该显示:
aaa
aaa
我有:
$words = explode(" ", $_POST['txt']);
for ($i=0; $i<count($words); $i++){
echo $words[$i] . " ";
这可以用foreach完成吗?
$words = explode(" ", $_POST['txt']);
$length = 3;
foreach($words as $word) {
// mb_strlen to take multibyte characters into account
if(mb_strlen($word) == $length) {
echo $word . "\n";
}
}
也许?
是的。
$length = 3;
$words = explode(" ", $_POST['txt']);
foreach ($words as $word) {
if (strlen($word) == $length) {
echo $word . ' ';
}
}
你可以用foreach
. 但是,如果$words
是一个数组,您可以利用以下数组函数之一array_filter()
:
$length = 3;
$words = array_filter($words, function($word) use ($length) {
return mb_strlen($word) == $length;
});
print_r($words);
注意:需要 PHP 5.3+。