【问题标题】:How can I remove the last empty space from my string inside array? [closed]如何从数组中的字符串中删除最后一个空格? [关闭]
【发布时间】:2018-10-07 04:27:11
【问题描述】:

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

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

【问题讨论】:

  • 试试php的rtrim()
  • @DevsiOdedra 我做了,它在代码中。看?但是还是不行
  • 你有 \r\n 字符在那里,使用rtrim() php.net/manual/en/function.rtrim.php 如上建议
  • 您还需要保存字符串。 $str = rtrim($str);。该字符串不作为参考传递。新行默认由 trim() 覆盖。无需手动定义。
  • 你缺少分配rtrim ($str, "\n");的结果应该是$str = rtrim ($str, "\n");

标签: php arrays string character-trimming


【解决方案1】:

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

Tha 说你可以像这样使用 array_map 和 trim :

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

【讨论】:

  • 他/她那里有新台词,trim() 也不够用
  • @pokeybit - 是的。演示:3v4l.org/u1HO4
  • @pokeybit 这是:3v4l.org/PvEq4
  • 道歉我删除了我的反对票@Angelure
【解决方案2】:

您没有分配rtrim ($str, "\n"); 的结果。所以你的变量$str 没有改变。

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

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

$str = rtrim($str);

【讨论】:

    猜你喜欢
    • 2013-07-28
    • 1970-01-01
    • 2020-03-18
    • 2021-12-14
    • 1970-01-01
    • 2022-01-14
    • 2013-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多