MeltingDog
MeltingDog

Reputation: 15424

PHP: Exploding string by space includes spaces in array

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

Answers (5)

Passionate Coder
Passionate Coder

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

Patrick Mlr
Patrick Mlr

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

Master Yoda
Master Yoda

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

Bartosz Zasada
Bartosz Zasada

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

Poiz
Poiz

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

Related Questions