preg_split之后只需要返回非空数组值


Need to only return non-empty array values after preg_split

我返回的是输入到以换行符分隔的文本区域中的内容,如下所示:

06/10/2014 
06/11/2014

然而,我想避免这样一个事实,如果用户应该在文本框中以这种方式输入它(太多的空格):

06/10/2014

06/11/2014

我想说明这一点,但仍然只返回两个日期值,而不是额外的换行。如果返回第二个示例,数组看起来像这样:

PHP代码

$date_array = preg_split("/('r'n|'r|'n)/", $row['blackout_date'], -1, PREG_SPLIT_NO_EMPTY);
            // check for any extra returns or white spaces
            print_r($date_array);
数组

Array ( [0] => 06/11/2014
[1] => 
[2] => 06/12/2014 )

我想去掉那个空数组,但是array_filter不起作用。有什么建议吗?谢谢!

模式中|的优先级工作方式可能会留下不被认为是空的'n'r。试一试:

$date_array = preg_split("/'s+/", $row['blackout_date'], -1, PREG_SPLIT_NO_EMPTY);

在这种情况下,PREG_SPLIT_NO_EMPTY可能不需要,但我离开它是安全的。

就像这样使用array_filter来删除空数组值:

// Set the test data.
$test_data = <<<EOT
06/10/2014

06/11/2014
EOT;
// Check for any extra returns or white spaces.
$date_array = preg_split("/('r'n|'r|'n)/", $test_data, -1);
// Use 'array_filer' and 'array_values' to shake out the date array.
$date_array = array_values(array_filter($date_array));
// Check the cleaned date array by dumping the data.
echo '<pre>';
print_r($date_array);
echo '</pre>';

输出将是:

Array
(
    [0] => 06/10/2014
    [1] => 06/11/2014
)

或者以另一种方式处理空行问题:也许您应该使用preg_match_all来匹配您想要的实际日期,而不是使用preg_split分割?

// Set the test data.
$test_data = <<<EOT
06/10/2014

06/11/2014
EOT;
// Match all of the dates that match your format.
preg_match_all('/[0-9]{2}'/[0-9]{2}'/[0-9]{4}/is', $test_data, $matches);
// Set the date array based on the dates matched.
$date_array = array_values(array_filter($matches[0]));
// Check the cleaned date array by dumping the data.
echo '<pre>';
print_r($date_array);
echo '</pre>';

输出是:

Array
(
    [0] => 06/10/2014
    [1] => 06/11/2014
)

preg_split() with 'r'n pattern可以用来解决你的问题。

$date_array = preg_split('/['r'n]+/', $row['blackout_date'], -1, PREG_SPLIT_NO_EMPTY);