如果“,”之后有任何字符,则在它们之间按<space>

I have some strings like these:

$str = "it is a test,it is a test";
$str = "it is a test ,it is a test";
$str = "it is a test, it is a test";
$str = "it is a test , it is a test";

Now I want this for all of them:

$str = "it is a test, it is a test";

Now, I can do that in several steps:

  1. str_replace(" , ",",","$str");
  2. str_replace(" ,",",","$str");
  3. str_replace(", ",",","$str");
  4. str_replace(",",", ","$str");

Then the output will be what I want. Now I want to know, is there any REGEX code for doing that in one step?

You can use this and replace it with ,[space]

\s*,\s*

that is:

preg_replace('/\s*,\s*/', ', ', $str);