php explode:使用空格分隔符将字符串拆分为单词

Har*_*iec 19 php regex arrays explode preg-match

$str = "This is a    string";
$words = explode(" ", $str);
Run Code Online (Sandbox Code Playgroud)

工作正常,但空间仍然进入数组:

$words === array ('This', 'is', 'a', '', '', '', 'string');//true
Run Code Online (Sandbox Code Playgroud)

我更喜欢只有没有空格的单词,并保留有关空格数量的信息.

$words === array ('This', 'is', 'a', 'string');//true
$spaces === array(1,1,4);//true
Run Code Online (Sandbox Code Playgroud)

刚添加:(1, 1, 4)表示第一个单词后面的一个空格,第二个单词后面的一个空格和第三个单词后面的4个空格.

有什么方法可以快速完成吗?

谢谢.

Alm*_* Do 29

要将String拆分为数组,您应该使用preg_split:

$string = 'This is a    string';
$data   = preg_split('/\s+/', $string);
Run Code Online (Sandbox Code Playgroud)

你的第二部分(计算空间):

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