如何使用 PHP 从字符串中删除最后一个逗号?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15408691/
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 the last comma from a string using PHP?
提问by JoJo
I am using a loop to get values from my database and my result is like:
我正在使用循环从我的数据库中获取值,我的结果如下:
'name', 'name2', 'name3',
And I want it like this:
我想要这样:
'name', 'name2', 'name3'
I want to remove the comma after the last value of the loop.
我想在循环的最后一个值之后删除逗号。
回答by Ander2
回答by Boaz - Reinstate Monica
Try:
尝试:
$string = "'name', 'name2', 'name3',";
$string = rtrim($string,',');
回答by VijayS91
Try the below code:
试试下面的代码:
$my_string = "'name', 'name2', 'name3',";
echo substr(trim($my_string), 0, -1);
Use this code to remove the last character of the string.
使用此代码删除字符串的最后一个字符。
回答by Annie Chandel
You can use substrfunction to remove this.
您可以使用substr函数来删除它。
$t_string = "'test1', 'test2', 'test3',";
echo substr($t_string, 0, -1);
回答by Jitendra Tyagi
rtrimfunction
rtrim功能
rtrim($my_string,',');
Second parameter indicates that comma to be deleted from right side.
第二个参数表示要从右侧删除的逗号。
回答by Owais Alam
At first I tried without a space rtrim($arraynama,",");and got an invalid result.
起初我在没有空格的情况下尝试rtrim($arraynama,",");并得到了无效的结果。
Then I added a space and got a valid result:
然后我添加了一个空格并得到了一个有效的结果:
$newarraynama=rtrim($arraynama,", ");
回答by Sankalp Mishra
use rtrim()
用 rtrim()
rtrim($string,',');
回答by Ashok Khot
It will impact your script if you work with multi-byte text that you substring from. If this is the case, I higly recommend enabling mb_* functions in your php.ini or do this ini_set("mbstring.func_overload", 2);
如果您使用子字符串中的多字节文本,它将影响您的脚本。如果是这种情况,我强烈建议您在 php.ini 中启用 mb_* 函数或执行此操作ini_set("mbstring.func_overload", 2);
$string = "'test1', 'test2', 'test3',";
echo mb_substr($string, 0, -1);
回答by Ketan Savaliya
its as simple as:
它很简单:
$commaseparated_string = name,name2,name3,;
$result = rtrim($commaseparated_string,',');
回答by khandaniel
It is better to use implode for that purpose. Implode is easy and awesome:
为此目的最好使用内爆。内爆既简单又很棒:
$array = ['name1', 'name2', 'name3'];
$str = implode(', ', $array);
Output:
输出:
name1, name2, name3

