【问题标题】:How to delete the last character in the text? [duplicate]如何删除文本中的最后一个字符? [复制]
【发布时间】:2011-10-01 23:08:32
【问题描述】:

可能重复:
remove last character from string

我想删除文本中的最后一个字符..

例如

我的字符串:example text
二:example tex

怎么做?

【问题讨论】:

标签: php string substr


【解决方案1】:

使用substr

$text = 'Example Text';
$text = substr($text, 0, -1)

substr 接受三个参数,原始文本、start 和 length,它从给定长度的 start 处返回原始文本的子字符串。如果长度为负数,该字符数将从字符串中排除,这就是为什么使用值 -1 来排除字符串中的最后一个字符。

【讨论】:

    【解决方案2】:

    使用substr,获取原字符串的子串:

    $str = 'example text';
    $newStr = substr($str, 0, -1); // "example text"
    

    0 表示“从头开始”,-1 表示“直到结束前一个字符”。

    【讨论】:

      【解决方案3】:

      使用这个

      substr($string, 0, -1);
      

      【讨论】:

        【解决方案4】:

        简单明了

        $str[strlen($str) - 1] = '';

        做你的事。

        字符串实际上是 php.ini 中的一个字符数组。因此,您可以将最后一个索引设置为空字符串。 使用 unset() 会更好,但 php 不允许取消设置字符串索引。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-09-08
          • 1970-01-01
          • 2014-09-15
          • 2016-02-29
          • 1970-01-01
          相关资源
          最近更新 更多