php 从字符串中删除最后一个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5592994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 21:54:35  来源:igfitidea点击:

Remove the last character from a string

php

提问by I-M-JM

What is fastest way to remove the last character from a string?

从字符串中删除最后一个字符的最快方法是什么?

I have a string like

我有一个像

a,b,c,d,e,

I would like to remove the last ',' and get the remaining string back:

我想删除最后一个 ',' 并取回剩余的字符串:

OUTPUT: a,b,c,d,e

What is the fastest way to do this?

什么是最快的方法来做到这一点?

回答by

First, I try without a space, rtrim($arraynama, ",");and get an error result.

首先,我尝试没有空格,rtrim($arraynama, ",");并得到错误结果。

Then I add a space and get a good result:

然后我添加一个空格并得到一个很好的结果:

$newarraynama = rtrim($arraynama, ", ");

回答by Nicola Peluchetti

You can use substr:

您可以使用substr

echo substr('a,b,c,d,e,', 0, -1);
# => 'a,b,c,d,e'

回答by bart

An alternative to substris the following, as a function:

substr作为一个函数,替代如下:

substr_replace($string, "", -1)

Is it the fastest? I don't know, but I'm willing to bet these alternatives are all so fast that it just doesn't matter.

它是最快的吗?我不知道,但我敢打赌这些替代方案都太快了,以至于无关紧要

回答by Bas van Ommen

You can use

您可以使用

substr(string $string, int $start, int[optional] $length=null);

See substrin the PHP documentation. It returns part of a string.

请参阅PHP 文档中的substr。它返回字符串的一部分。