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?

5 Answers 5

4

Use preg_split() instead of explode():

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

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

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

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

Comments

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"
}

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.