0

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);
2
  • Regular expressions are your friend. :) Commented Apr 17, 2012 at 18:22
  • Hm... substr_count will give me 6 for the example above. preg_split to split by (any num of) will split the string into 3 words. How will I know 6=5+1, but not 3+3? Commented Apr 17, 2012 at 18:34

3 Answers 3

2

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);
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

He just needs the number of spaces.
How does this answer the OP's question?
I was blinded by the 'I wish to split a text string into words separated by spaces' part
1

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

1 Comment

That's elegant, compact and I believe it's fast (faster than using for statement I guess). It works. Thank you.
0

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

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

Wouldn't that work for you?

3 Comments

Thanks, but that doesn't say how many spaces are between each pair of words at all, even doesn't say the total number of spaces.
@Haradzieniec I thought you wanted to split up each word? What word has spaces in them? :/ The number of spaces is in $spaces (number of words in array - 1)
I put an explanation, an example into a question. Thank 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.