Reputation: 15424
I have string with several spaces, including double spaces and spaces at the start and end of the string:
12 345 67 89
I want to add just the numbers into array so used:
explode(" ", $s);
But this adds spaces to to the array as well.
Is there a way to add only the numbers to the array?
Upvotes: 0
Views: 61
Reputation: 7294
Try this trim
with preg_split
$str = " 12 345 67 89";
$data = preg_split('/\s+/', trim($str), $str);
trim()
is used to remove space before the first and behind the last element. (which preg_split() doesn't do - it removes only spaces around the commas)
Upvotes: 0
Reputation: 2965
Try this:
$numbers = " 12 345 67 89";
$numbers = explode(" ", trim($numbers));
$i = 0;
foreach ($numbers as $number) {
if ($number == "") {
unset($numbers[$i]);
}
$i++;
}
var_dump(array_values($numbers));
Output:
array(4) {
[0]=>
string(2) "12"
[1]=>
string(3) "345"
[2]=>
string(2) "67"
[3]=>
string(2) "89"
}
Upvotes: 0
Reputation: 531
i have applied this code , please have a look
<?php
$data = "12 345 67 89";
$data = preg_replace('/\s+/', ' ',$data);
var_dump(explode(' ',$data));
die;
?>
i suppose most of the code is understandable to you , so i just explain this to you :
preg_replace('/\s+/', ' ',$data)
in this code , the preg_replace replaces one or more occurences of ' ' into just one ' '.
Upvotes: 0
Reputation: 3900
Use preg_split()
instead of explode()
:
preg_split('/\s+/', $str);
This will split the string using one or more space as a separator.
Upvotes: 4
Reputation: 7617
If you want to take all spaces into consideration at once, why not use preg_split()
like so:
<?php
$str = "12 345 67 89";
$res = preg_split("#\s+#", $str);
Upvotes: 0