0

I have an array with a couple of words, and I'm trying to explode it at only one whitespace, but its counting whitespaces in as well when exploding for some reason. How do I stop this?

<?php

$string = "I'm just            so peachy, right now";
$string = explode(" ", $string);

$count = count($string);
$tempCount = 0;

while ($tempCount < $count) {
echo $string[$tempCount]."$tempCount<br>";
$tempCount++;
}

?>

Actual Output:

I'm0
just1
2
3
4
5
6
7
8
9
10
11
12
so13
peachy,14
right15
now16

Expected Output:

I'm0
just1
so2
peachy,3
right4
now5

1 Answer 1

5

Use a preg_split, http://php.net/manual/en/function.preg-split.php, which will use a regex so you can tell it to keep all continuous white-spaces as one.

$string = 'I\'m just            so peachy, right now';
$spaced = preg_split('~\h+~', $string);
print_r($spaced);

Output:

Array
(
    [0] => I'm
    [1] => just
    [2] => so
    [3] => peachy,
    [4] => right
    [5] => now
)

PHP Demo: http://3v4l.org/a5cg5
Regex Demo: https://regex101.com/r/vO1qU0/1

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

8 Comments

What does ~\h+~ mean?
Horizontal whitespace character (+ means one or more of).
I forget about preg_split(). Great solution.
Should have added the regex demo at first. Yea, the \h is for an inline space (horizontal whitespace). The + is for one or more occurance of the previous character. The ~ are delimiters.
@Zanderwar You guys need to tag whoever down voted you.
|

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.