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

后端 未结 6 2065
粉色の甜心
粉色の甜心 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条回答
  •  春和景丽
    2020-12-08 16:04

    Here is one way, splitting the string and running a regex once, then parsing the results to see which segments were captured as the split (and therefore only whitespace), or which ones are words:

    $temp = preg_split('/(\s+)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
    
    $spaces = array();
    $words = array_reduce( $temp, function( &$result, $item) use ( &$spaces) {
        if( strlen( trim( $item)) === 0) {
            $spaces[] = strlen( $item);
        } else {
            $result[] = $item;
        }
        return $result;
    }, array());
    

    You can see from this demo that $words is:

    Array
    (
        [0] => This
        [1] => is
        [2] => a
        [3] => string
    )
    

    And $spaces is:

    Array
    (
        [0] => 1
        [1] => 1
        [2] => 4
    )
    

提交回复
热议问题