如何从数组中的字符串中删除最后一个空格?

时间:2018-04-26 12:53:58

标签: php arrays string character-trimming

我正在从文件中创建一个数组:

$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);

但是在我的结果数组中,值的末尾总是有空格,我无法摆脱它们:

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
"
  }
}

2 个答案:

答案 0 :(得分:6)

您错过了分配rtrim ($str, "\n");的结果。因此,您的变量$str不会更改。

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

或者,默认情况下,删除所有空格字符(" \t\n\r\0\x0B"):

$str = rtrim($str);

答案 1 :(得分:2)

您可以使用rtrim()函数删除字符串开头和结尾的空格,但逐个使用它。 您也可以参考对此帖子的回复:How can I trim all strings in an Array?

Tha说您可以使用array_map和trim:

$result = array_map('rtrim', $source_array);