将csv字符串转换为带有空格而不是php中逗号的字符串
我有一个像这样以逗号分隔的字符串,
$str = "john, alice, mary,joy";
有些在逗号后有空格,有些则没有。我想要做的是删除所有逗号并使它们像这样:
$str = "john alic mary joy";
What is the best way to do this in php?
I'm having a string which is comma seperated like this
$str = "john, alice, mary,joy";
Some are having space after comma and some don't. What I want to do is remove all the commas and make them like this:
$str = "john alic mary joy";
What is the best way to do this in php?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当逗号后面最多有一个空格时,str_replace是最简单的解决方案:
如果可以有多个空格,那么我会使用正则表达式解决方案。 (参见icktoofay的回答)
str_replace
is the simplest solution when there is at most one space after the comma:If there can be multiple spaces, then I would go with the regex solution. (see icktoofay's answer)
尽管正则表达式可能不是最好的方法,但像这样的简单正则表达式可以转换该数据:
Although regular expressions may not be the best way, a simple regular expression such as this could transform that data:
echo str_replace(',',' ',str_replace(' ','',$str));
echo str_replace(',',' ',str_replace(' ','',$str));
非正则表达式方法:
A non-regex approach: