Haradzieniec
Haradzieniec

Reputation: 9340

php explode() function issue - spaces

I wish to split a text string into words separated by spaces. I use

$words=explode(" ", $text);

Unfortunately, this method doesn't work well for me, because I want to know how many spaces are in between.

Is there any better way to do that than going through the whole $text, symbol by symbol, using while statement to fill out $spaces ( $spaces=array(); ) with integers (number of spaces, in most cases it is 1) and read text into $words=array() symbol by symbol?

Here is an additional explanation.

$text="Hello_world_____123"; //symbol "_" actually means a space

Needed:

$words=("Hello","world","123");
$spaces=(1,5);

Upvotes: 0

Views: 366

Answers (3)

FtDRbwLXw6
FtDRbwLXw6

Reputation: 28889

There are many ways to do what you're trying to do, but I would probably choose a combination of preg_split() and array_map():

$text = 'Hello world     123';
$words = preg_split('/\s+/', $text, NULL, PREG_SPLIT_NO_EMPTY);
$spaces = array_map(function ($sp) {
    return strlen($sp);
}, preg_split('/\S+/', $text, NULL, PREG_SPLIT_NO_EMPTY));

var_dump($words, $spaces);

Output:

array(3) {
  [0]=>
  string(5) "Hello"
  [1]=>
  string(5) "world"
  [2]=>
  string(3) "123"
}
array(2) {
  [0]=>
  int(1)
  [1]=>
  int(5)
}

Upvotes: 1

Tchoupi
Tchoupi

Reputation: 14691

Use a regular expression instead:

$words = preg_split('/\s+/', $text)

EDIT

$spaces = array();
$results = preg_split('/[^\s]+/', $text);
foreach ($results as $result) {
  if (strlen($result) > 0) {
     $spaces [] = strlen($result);
  }
}

Upvotes: 2

Ozzy
Ozzy

Reputation: 8312

You can still get the number of spaces inbetween like this:

$words = explode(" ", $text);
$spaces = sizeof($words)-1;

Wouldn't that work for you?

Upvotes: 0

Related Questions