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

时间:2015-11-15 15:13:19

标签: php regex string

我有一些像这样的字符串:

$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";

现在我想要所有这些:

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

现在,我可以分几步完成:

  1. str_replace(" , ",",","$str");
  2. str_replace(" ,",",","$str");
  3. str_replace(", ",",","$str");
  4. str_replace(",",", ","$str");
  5. 然后输出将是我想要的。现在我想知道,有没有任何REGEX代码可以一步完成呢?

1 个答案:

答案 0 :(得分:4)

您可以使用它并将其替换为,[space]

\s*,\s*

即:

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