Exploding a String In PHP
How do i开发者_如何学Python 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',
)
$array = explode('||', trim($string, '|'));
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.
$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
)
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.
You can do:
explode('||',substr($str,2));
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");
精彩评论