爆炸排列并打印每个元素作为列表项?

时间:2018-08-24 10:17:08

标签: php explode

我在数据库的表字段中有一组数字,这些数字用逗号'| 1 || 10 || 12 |'分隔。我正在尝试执行以下操作:

$array =  explode('|', $set_of_numbers);

answer

["","1","","10","","12",""]

我需要

["1","10","12"]

可以完成,谢谢您先前

5 个答案:

答案 0 :(得分:1)

使用此功能,array_filter()函数将从数组中删除空值/空白值并返回仅包含值的数组。

$set_of_numbers = '|1||10||12|';
$array =  array_filter(explode('|', $set_of_numbers));

答案 1 :(得分:1)

您可以尝试一下吗

$set_of_numbers = '|1||10||12|';
$array = array_filter(explode("|", $set_of_numbers), function($value) { return $value!== ''; });

您可以使用它,我在phpfiddle上进行了测试。

答案 2 :(得分:0)

尝试一下。 这将起作用。

$set_of_numbers = '|1||10||12|';
$array =  explode('|', $set_of_numbers);
$array = array_filter($array);

答案 3 :(得分:0)

您还可以使用正则表达式:

<?php

$a = '|1||10||12|';
$matches = [];
preg_match_all('/(\d+)/', $a, $matches);
var_dump($matches[1]);

http://php.net/manual/en/function.preg-match-all.php

答案 4 :(得分:-1)

尝试一下

$array = trim($array, '|');
$array = explode('||', $set_of_numbers);