php 如何删除字符串末尾的逗号?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1642698/
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
how do i remove a comma off the end of a string?
提问by zeckdude
I want to remove the comma off the end of a string. As it is now i am using
我想删除字符串末尾的逗号。就像现在我正在使用
$string = substr($string,0,-1);
but that only removes the last character of the string. I am adding the string dynamically, so sometimes there is no comma at the end of the string. How can I have PHP remove the comma off the end of the string if there is one at the end of it?
但这只会删除字符串的最后一个字符。我正在动态添加字符串,因此有时字符串末尾没有逗号。如果字符串末尾有逗号,我如何让 PHP 删除字符串末尾的逗号?
回答by Sigurd
回答by Ben Russell
This is a classic question, with two solutions. If you want to remove exactly one comma, which may or may not be there, use:
这是一个经典的问题,有两种解决方案。如果要删除一个逗号(可能存在也可能不存在),请使用:
if (substr($string, -1, 1) == ',')
{
$string = substr($string, 0, -1);
}
If you want to remove all commas from the end of a line use the simpler:
如果要删除行尾的所有逗号,请使用更简单的:
$string = rtrim($string, ',');
The rtrim function (and corresponding ltrim for left trim) is very useful as you can specify a range of characters to remove, i.e. to remove commas and trailing whitespace you would write:
rtrim 函数(以及对应的左修剪的 ltrim)非常有用,因为您可以指定要删除的字符范围,即删除您将编写的逗号和尾随空格:
$string = rtrim($string, ", \t\n");
回答by user187291
i guess you're concatenating something in the loop, like
我猜你在循环中连接一些东西,比如
foreach($a as $b)
$string .= $b . ',';
much better is to collect items in an array and then join it with a delimiter you need
更好的是收集数组中的项目,然后使用您需要的分隔符加入它
foreach($a as $b)
$result[] = $b;
$result = implode(',', $result);
this solves trailing and double delimiter problems that usually occur with concatenation
这解决了通常与连接一起出现的尾随和双分隔符问题
回答by cesar.mi
If you're concatenating something in the loop, you can do it in this way too:
如果你在循环中连接某些东西,你也可以这样做:
$coma = "";
foreach($a as $b){
$string .= $coma.$b;
$coma = ",";
}
回答by Anand Shah
have a look at the rtrim function
看看 rtrim 函数
rtrim ($string , ",");
the above line will remove a char if the last char is a comma
如果最后一个字符是逗号,则上面的行将删除一个字符
回答by AlexWilson
A simple regular expression would work
一个简单的正则表达式就可以工作
$string = preg_replace("/,$/", "", $string)
回答by mepo
rtrim ($string , ","); is the easiest way.
rtrim ($string , ","); 是最简单的方法。
回答by TigerTiger
if(substr($str, -1, 1) == ',') {
$str = substr($str, 0, -1);
}
回答by Kaivosukeltaja
Precede that with:
在此之前:
if(substr($string, -1)==",")
回答by zzapper
I had a pesky "invisible" space at the end of my string and had to do this
我的字符串末尾有一个讨厌的“隐形”空间,不得不这样做
$update_sql=rtrim(trim($update_sql),',');
But a solution above is better
但是上面的解决方案更好
$update_sql=rtrim($update_sql,', ');

