tags:

views:

230

answers:

6

How do i explode this string '||25||34||73||94||116||128' i need to have a array like this

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

explode("||", $array); didnt work for me i get this array

array (
 0 => '',
 1 => '25',
 2 => '34',
 3 => '73',
 4 => '94',
 5 => '116',
 6 => '128',
) 
+12  A: 
$array = explode('||', trim($string, '|'));
Adam Kiss
Thanks this worked for me
streetparade
A: 

You can do:

explode('||',substr($str,2));
codaddict
+4  A: 

A solution, especially if you can have empty values in the middle of the string, could be to use preg_split and its PREG_SPLIT_NO_EMPTY flag :

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

Will give you :

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'll never have empty values in the middle of the string, though, using explode will be faster, even if you have to remove the || at the beginning and end of the string before calling it.

Pascal MARTIN
+1  A: 
$str='||25||34||73||94||116||128';
$s = array_filter(explode("||",$str),is_numeric);
print_r($s);

output

$ php test.php
Array
(
    [1] => 25
    [2] => 34
    [3] => 73
    [4] => 94
    [5] => 116
    [6] => 128
)
ghostdog74
What if there is a value `0`?
Gumbo
A: 

Besides the already mentioned solutions, you could also filter out the empty values afterwards:

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

This example uses an anonymous function that you would need to replace if you’re not using PHP 5.3 or greater, either using create_function:

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

Or with a predefined function:

function isEmptyString($str) {
    return trim($str) === "";
}
$arr = array_filter(explode("||", $str), "isEmptyString");
Gumbo
+1  A: 

Since one of your previous questions was how to store and update such a string in MySQL ...let's assume for a moment one of your future tasks will be to find out if a certain value is in this array/string or to find/count all records that have a certain value in this array.
In that case you might want to start normalizing your table now.

VolkerK