How can I strip whitespace only elements from an array?

前端 未结 5 1325
有刺的猬
有刺的猬 2021-01-23 05:54

How I can remove all elements of an array that contain just whitespace, not whitespace in an element like \"foobar \" but just empty array elements like <

5条回答
  •  伪装坚强ぢ
    2021-01-23 06:16

    preg_grep() is your friend.

    $array = array("This", " ", "is", " ", "a", " ", "test.");
    
    $array = preg_grep('/^\s*\z/', $array, PREG_GREP_INVERT);
    
    var_dump($array);
    

    CodePad.

    This will drop all array members of which the string is blank or only consist of whitespace according to \s character class (spaces, tabs, and line breaks).

    Output

    array(4) {
      [0]=>
      string(4) "This"
      [2]=>
      string(2) "is"
      [4]=>
      string(1) "a"
      [6]=>
      string(5) "test."
    }
    

提交回复
热议问题