-2

例子:

a
aaa
aaaaa
aaa
aa

如果给定长度为 3,那么它应该显示:

aaa
aaa

我有:

$words = explode(" ", $_POST['txt']);
for ($i=0; $i<count($words); $i++){ 
echo $words[$i] . " ";

这可以用foreach完成吗?

4

3 回答 3

2
$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";
    }
}

也许?

于 2013-06-19T19:27:51.403 回答
2

是的。

$length = 3;
$words = explode(" ", $_POST['txt']);

foreach ($words as $word) {
  if (strlen($word) == $length) {
    echo $word . ' ';
  }
}
于 2013-06-19T19:27:51.710 回答
2

你可以用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+。

于 2013-06-19T19:29:19.450 回答