0

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?

MeltingDog
  • 14,310
  • 43
  • 165
  • 295

5 Answers5

4

Use preg_split() instead of explode():

preg_split('/\s+/', $str);

This will split the string using one or more space as a separator.

Bartosz Zasada
  • 3,762
  • 2
  • 19
  • 25
0

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);
Poiz
  • 7,611
  • 2
  • 15
  • 17
0

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 ' '.

Master Yoda
  • 531
  • 8
  • 22
0

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"
}
Patrick Mlr
  • 2,955
  • 2
  • 16
  • 25
0

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)

Passionate Coder
  • 7,154
  • 2
  • 19
  • 44