Search code examples
phpexplode

How to avoid empty elements by splitting a string on one or more consecutive spaces?


I use file_get_contents for give answer from remote address and explode for create array give data.

For this I use next code:

function test() {
    $project_key ='fg54gth5k7';
    $postdata = http_build_query(
        array(
            'code' => $project_key
        )
    );
    $opts = array('http' =>
        array(
            'method'  => 'POST',
            'header'  => 'Content-type: application/x-www-form-urlencoded',
            'content' => $postdata
        )
    );
    $context = stream_context_create($opts);
    $result = file_get_contents('http://test.com/', false, $context);
    return $result;
}
    
$res = test();
echo $res;
  
$part = explode(' ', $res);
var_dump($part);

echo $res return row:

3434343 http://test.com/index.php?r=site/stepone
&temptoken=c68c0ae1cece433fe5d6f6578cc0a9b6 OK68 OK Redirect 
http://test.com/index.php?r=site/stepone&temptoken=c68c0ae1cece433fe5d6f6578cc0a9b6 0

var_dump() return array

array(5) { 
[0]=> string(8) "3434343" 
[1]=> string(0) "" 
[2]=> string(0) "" 
[3]=> string(110) "http://test.com/index.php?r=site/stepone
    &temptoken=c68c0ae1cece433fe5d6f6578cc0a9b6 OK68 OK Redirect"
 
[4]=> string(100) "http://test.com/index.php?
    r=site/stepone&temptoken=c68c0ae1cece433fe5d6f6578cc0a9b6 0 " 

}

Tell me please why am I getting the wrong array?

array should been next:

array(10) { 
    [0]=> string(8) "3434343" 
    [1]=> string(0) "" 
    [2]=> string(0) "" 
    [3]=> string(110) "http://test.com/index.php?r=site/stepone
        &temptoken=c68c0ae1cece433fe5d6f6578cc0a9b6"
    [4]=> string(4) "OK68 OK Redirect"
    [5]=> string(2) "OK Redirect"
    [6]=> string(8) "Redirect"
    [7]=> string(100) "http://test.com/index.php?
        r=site/stepone&temptoken=c68c0ae1cece433fe5d6f6578cc0a9b6"
    [8]=> string(1) "0"
    [9]=> string(0) ""

Tell me please where error?


Solution

  • They might not be the space character, but tabs etc.

    Use preg_split with the delimiter [\s]+.

    \s stands for "whitespace character". It includes [ \t\r\n] generally.

    (Reference)