Search code examples
phparraysstringcharacter-trimming

How can I remove the last empty space from my string inside array?


I am creating a array from a file:

$handle = fopen("inputfile.txt", "r");
if ($handle) {
    while (($str = fgets($handle)) !== false) {
           if (strlen($str) && $str[0] == '#') {
                    $pdate = substr($str, 1);
                    $date = rtrim($pdate);
                    $formatted = DateTime::createFromFormat('* M d H:i:s T Y',$date);
                }
                rtrim ($str, "\n");
                $exp = explode ('=', $str);
                if(count($exp) == 2){
                    $exp2 = explode('.', $exp[0]);  
                    if( count($exp2) == 2 ) {
                        if($exp2[1] == "dateTime"){
                            $s = str_replace("\\","",$exp[1]);
                            $d = strtotime($s);
                            $dateTime = date('Y-m-d H:i:s', $d);
                            $properties [$exp2[0]][$exp2[1]] = $dateTime;
                        } else {
                            $properties [$exp2[0]][$exp2[1]] = $exp[1];
                        }
                    } else {
                        $properties [$exp[0]] = $exp[1];
                    }
                } 
    }
    var_dump($properties); 
    fclose($handle);
} else {
    // error opening the file.
} 

var_dump($properties);

But in my result array there are always white spaces at the end of the values and I cannot get rid of them:

array(5) {
  ["folder"]=>
  array(5) {
    ["dateTime"]=>
    string(19) "2016-10-12 19:46:25"
    ["one"]=>
    string(47) "abc def
"
    ["two"]=>
    string(33) "ghi jk
"
    ["three"]=>
    string(150) "lm no
"
    ["four"]=>
    string(8) "pqr st
"
  }
}

Solution

  • You're missing to assign the result of rtrim ($str, "\n");. So your variable $str is not changed.

    $str = rtrim($str, "\n");
    

    Or, by default, to remove all whitespace characters (" \t\n\r\0\x0B"):

    $str = rtrim($str);