仅播放具有给定长度的单词 - 字符串 php


dissplay only the words that have a given length - string php

示例:

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+。