只显示具有给定长度的单词 - 字符串php

时间:2013-06-19 19:25:08

标签: php string

示例:

a
aaa
aaaaa
aaa
aa

如果给定长度为3则应显示:

aaa
aaa

我有:

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

这可以用foreach完成吗?

3 个答案:

答案 0 :(得分: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";
    }
}

也许?

答案 1 :(得分:2)

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

foreach ($words as $word) {
  if (strlen($word) == $length) {
    echo $word . ' ';
  }
}

答案 2 :(得分: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 +。