Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

arrays - php explode: split string into words by using space a delimiter

$str = "This is a    string";
$words = explode(" ", $str);

Works fine, but spaces still go into array:

$words === array ('This', 'is', 'a', '', '', '', 'string');//true

I would prefer to have words only with no spaces and keep the information about the number of spaces separate.

$words === array ('This', 'is', 'a', 'string');//true
$spaces === array(1,1,4);//true

Just added: (1, 1, 4) means one space after the first word, one space after the second word and 4 spaces after the third word.

Is there any way to do it fast?

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For splitting the String into an array, you should use preg_split:

$string = 'This is a    string';
$data   = preg_split('/s+/', $string);

Your second part (counting spaces):

$string = 'This is a    string';
preg_match_all('/s+/', $string, $matches);
$result = array_map('strlen', $matches[0]);// [1, 1, 4]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...