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

后端 未结 6 2072
粉色の甜心
粉色の甜心 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 15:48

    Here are the results of performance tests:

    $str = "This is a    string";
    
    var_dump(time());
    
    for ($i=1;$i<100000;$i++){
    //Alma Do Mundo  - the winner
    $rgData = preg_split('/\s+/', $str);
    
    
    preg_match_all('/\s+/', $str, $rgMatches);
    $rgResult = array_map('strlen', $rgMatches[0]);// [1,1,4]
    
    
    }
    print_r($rgData); print_r( $rgResult);
    var_dump(time());
    
    
    
    
    for ($i=1;$i<100000;$i++){
    //nickb
    $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());
    }
    
    
    print_r( $words); print_r( $spaces);
    var_dump(time());
    

    int(1378392870) Array ( [0] => This [1] => is [2] => a [3] => string ) Array ( [0] => 1 [1] => 1 [2] => 4 ) int(1378392871) Array ( [0] => This [1] => is [2] => a [3] => string ) Array ( [0] => 1 [1] => 1 [2] => 4 ) int(1378392873)

提交回复
热议问题