开发者

converting csv string to a string with spaces instead of commas 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?


str_replace is the simplest solution when there is at most one space after the comma:

$str = str_replace(array(', ', ','), ' ', $str);

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:

$str = preg_replace("/ *,+ */", " ", $str);


echo str_replace(',',' ',str_replace(' ','',$str));


A non-regex approach:

$str = str_replace(", ", ",", $str); # Remove single space after a comma
$str = implode(' ', explode(',',str));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜