【问题标题】:How can I trim/remove spaces from the end of a string in PHP?如何在 PHP 中修剪/删除字符串末尾的空格?
【发布时间】:2017-08-16 10:00:00
【问题描述】:

我有一个像“Tom Jerry”这样的字符串。我想从字符串末尾修剪多余的空间。 IE。理想的输出是“Tom Jerry”。我该怎么做?

【问题讨论】:

标签: php


【解决方案1】:

php中有trim方法:http://php.net/manual/en/function.trim.php

trim("Tom Jerry ");

【讨论】:

    【解决方案2】:

    使用修剪(字符串)函数??

    https://www.w3schools.com/php/func_string_trim.asp

    【讨论】:

    • 如果您指向官方 PHP 文档而不是第三方网站会更好
    【解决方案3】:

    您应该改用 rtrim。它将删除字符串末尾的多余空格,并且比使用 preg_replace 更快。

    $str = "This is a string.    ";
    echo rtrim($str);
    

    来源:Remove extra space at the end of string using preg_replace

    【讨论】:

      【解决方案4】:

      你可以使用trim()

      <?php
          $str = "tom jerry ";
          echo "Without trim: " . $str;
          echo "\n";
          echo "With trim: " . trim($str);
      ?>
      

      【讨论】:

        【解决方案5】:

        这里是如何使用trim()

        echo trim(' tom jerry   ');
        

        【讨论】:

          【解决方案6】:
          <?php
              trim("Tom Jerry ");
          ?>
          

          来自 w3schools 的更多 example

          【讨论】:

            【解决方案7】:

            对于一个字符串$string = " my name is Stark "; 使用ltrim($string)从字符串的开头修剪空格,使用rtrim($string)从字符串的末尾修剪空格,使用trim($string)从两端删除空格。如果您还想专门删除另一个字符,您还可以添加一个额外的参数(字符掩码),除了字符串末尾或开头的空格,例如尾随斜杠(" onefunnyurl.com/"

            【讨论】:

              猜你喜欢
              • 2013-09-11
              • 1970-01-01
              • 2021-09-16
              • 1970-01-01
              • 2017-05-24
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多