My string is
我的字符串是
$string = ",name2,name2,name3,";
I want to make it like;
我想让它变得像;
$string = "name2,name2,name3";
That is, to remove first and last comma from that string, any clue as to how to accomplish this either through regex or anything else?
也就是说,要从该字符串中删除第一个和最后一个逗号,有关如何通过正则表达式或其他任何方式完成此操作的任何线索?
Thanks.
谢谢。
2 个解决方案
#1
29
If you just want to remove the first and the last comma, you can use trim
如果您只想删除第一个和最后一个逗号,则可以使用trim
trim($string,",");
#2
4
You can use anchors for this:
您可以使用锚点:
$result = preg_replace('/^,|,$/', '', $subject);
If you want to match one or more commas at the start/end of the string:
如果要在字符串的开头/结尾处匹配一个或多个逗号:
$result = preg_replace('/^,+|,+$/', '', $subject);
And if there could be whitespace around those leading/trailing commas:
如果这些前导/尾随逗号周围可能有空格:
$result = preg_replace('/^[,\s]+|[\s,]+$/', '', $subject);
#1
29
If you just want to remove the first and the last comma, you can use trim
如果您只想删除第一个和最后一个逗号,则可以使用trim
trim($string,",");
#2
4
You can use anchors for this:
您可以使用锚点:
$result = preg_replace('/^,|,$/', '', $subject);
If you want to match one or more commas at the start/end of the string:
如果要在字符串的开头/结尾处匹配一个或多个逗号:
$result = preg_replace('/^,+|,+$/', '', $subject);
And if there could be whitespace around those leading/trailing commas:
如果这些前导/尾随逗号周围可能有空格:
$result = preg_replace('/^[,\s]+|[\s,]+$/', '', $subject);