0

是否有一种优雅的方式来处理数组值,允许使用简单的字数而不是 strlen() 或使用 str_word_count -> array_count_values 等来释放自己。

例如,我只想保留包含 x 个单词的数组值。

目前我正在使用。

<?php
class Functions
{
    public function processArray($array,$max,$min)
{
        foreach ($array as $value)
        {
        /* char count */
            if (strlen($value) < $max AND strlen($value) > $min) 
        /* word count */
            if (str_word_count($value,0) < $max AND str_word_count($value,0) > $min)
        {
        $array2[] = $value;
        }
    }
return $array2;
    }
}
$input = file_get_contents("files/scrape.txt");
$array = explode(".",$input);
$process = new Functions;
$output = implode(". ",$process->processArray($array,150,50));
print $output;
?>
4

1 回答 1

0

使用回调来自 PHP 5.4

function processArray($array,$func)
{
    $result = array();
    foreach ($array as $value)
    {
        if($func($value)){
            $result[] = $value;
        }
    }
    return $result;
}

processArray($array, function($a){
    return strlen($a) < 150 && strlen($a) > 50;
});

使用array_filter (来自 PHP 5.4 )

   array_filter($array, function($a){
        return strlen($a) < 150 && strlen($a) > 50;
   });

或(从 PHP 5 开始

function check($a){
   return strlen($a) < 150 && strlen($a) > 50;
}

array_filter($array, 'check');
于 2013-04-20T19:34:48.830 回答