PHP string explosion

How to blow this line '||25||34||73||94||116||128' I need an array like this

array (
 0 => '25',
 1 => '34',
 2 => '73',
 3 => '94',
 4 => '116',
 5 => '128'
)

explode ("||", $ array); not working for me, I get this array

array (
 0 => '',
 1 => '25',
 2 => '34',
 3 => '73',
 4 => '94',
 5 => '116',
 6 => '128',
) 
+3
source share
6 answers
$array = explode('||', trim($string, '|'));
+12
source

The solution, especially if you can have empty values ​​in the middle of the line , can be use and a flag : preg_splitPREG_SPLIT_NO_EMPTY

$str = '||25||34||73||94||116||128';
$array = preg_split('/\|\|/', $str, -1, PREG_SPLIT_NO_EMPTY);
var_dump($array);

You'll get:

array
  0 => string '25' (length=2)
  1 => string '34' (length=2)
  2 => string '73' (length=2)
  3 => string '94' (length=2)
  4 => string '116' (length=3)
  5 => string '128' (length=3)


If you never have empty values ​​in the middle of the line, usage explodewill be faster, even if you need to delete ||at the beginning and at the end of the line before calling.

+5
source
$str='||25||34||73||94||116||128';
$s = array_filter(explode("||",$str),is_numeric);
print_r($s);

$ php test.php
Array
(
    [1] => 25
    [2] => 34
    [3] => 73
    [4] => 94
    [5] => 116
    [6] => 128
)
+2

, ​​ MySQL... , / / , .
.

+1

:

explode('||',substr($str,2));
0

, :

$arr = array_filter(explode("||", $str), function($val) { return trim($val) === ""; });

, , PHP 5.3 , create_function:

$arr = array_filter(explode("||", $str), create_function('$val', 'return trim($val) === "";'));

:

function isEmptyString($str) {
    return trim($str) === "";
}
$arr = array_filter(explode("||", $str), "isEmptyString");
0
source

Source: https://habr.com/ru/post/1737670/


All Articles