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

后端 未结 6 2073
粉色の甜心
粉色の甜心 2020-12-08 15:17
$str = \"This is a    string\";
$words = explode(\" \", $str);

Works fine, but spaces still go into array:

$words === array (\'This         


        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 16:00

    You can use preg_split() for the first array:

    $str   = 'This is a    string';
    $words = preg_split('#\s+#', $str);
    

    And preg_match_all() for the $spaces array:

    preg_match_all('#\s+#', $str, $m);
    $spaces = array_map('strlen', $m[0]);
    

提交回复
热议问题