Php 只需在preg_分割后返回非空数组值
我将返回输入到由换行符分隔的文本区域的内容,如下所示:Php 只需在preg_分割后返回非空数组值,php,arrays,Php,Arrays,我将返回输入到由换行符分隔的文本区域的内容,如下所示: 06/10/2014 06/11/2014 但是,我想避免这样一个事实,即如果用户以这种方式在文本框中输入它(过多的中断会留下一个空白): 我想解释一下,但仍然只返回两个日期值,而不是额外的换行符。如果返回第二个示例,则数组如下所示: PHP代码 $date_array = preg_split("/(\r\n|\r|\n)/", $row['blackout_date'], -1, PREG_SPLIT_NO_EMPTY);
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);
排列
我想去掉那个空数组,但数组过滤器不起作用。有什么建议吗?谢谢 只需像这样使用即可除去空数组值:
// 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>';
或者用另一种方法来解决空行问题:也许你应该用它来匹配你想要的实际日期,而不是拆分日期
模式中的交替
|
中优先级的工作方式可能会留下不被视为空的零散\n
或\r
。尝试:
在这种情况下,可能不需要使用PREG\u SPLIT\u NO\u EMPTY
,但为了安全起见,我保留了它。使用\r\n模式可以解决您的问题
php.net上的伟大手册:PREG\u SPLIT\u NO\u EMPTY
也许吧?也试过了!不走运,但好主意。真的吗?好吧,该死,它对你有用,但在我的Wordpress网站上它对我不起作用。。。我使用foreach循环来迭代自定义字段。也许这引起了一个问题?对我来说也一样。贴出了我的答案<代码>阵列过滤器
工作。但是也许你不需要获取你不想要的数据,而应该使用preg\u match\u all
来获取你想要的准确数据。但是我已经尝试了数组过滤器。请注意我在原始帖子中所说的:)它仍然会生成上面的空数组。。。让我想知道如果不是null或“.”,实际返回的是什么。@jflay对我来说很好。也许你的正则表达式应该是/(\r\n |\r\n |\n\n)/
?@jflay检查我的更新答案。也许你应该使用preg\u match\u all
而不是拆分?谢谢你的回答,但由于质量问题,它已经发布供审查。虽然你的答案可能是正确的,但没有解释为什么,以及OP做错了什么。虽然通常不鼓励只使用代码的答案,但我不建议删除此选项,因为它确实有帮助。@EngineerDollery,谢谢您指出我的错误。无论如何,我有一个最新的答案。:)你的正则表达式模式有什么我不做的?非常有用,尽管我发现在将新行转换为标记的高级自定义字段中存在Wordpress格式问题。我选择不选择任何格式,所有的问题都消失了。谢谢你,伙计!
Array ( [0] => 06/11/2014
[1] =>
[2] => 06/12/2014 )
// 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
)
// 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
)
$date_array = preg_split("/\s+/", $row['blackout_date'], -1, PREG_SPLIT_NO_EMPTY);
$date_array = preg_split('/[\r\n]+/', $row['blackout_date'], -1, PREG_SPLIT_NO_EMPTY);