2015-11-15 28 views
1

我有一些字符串這樣的:如果有之後的任何字符「」,然後按他們之間<space>

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

然後輸出將是我想要的。現在我想知道,是否有任何REGEX代碼可以一步完成此操作?

回答

4

您可以使用此與,[space]

\s*,\s* 

即替換:

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

他希望逗號後添加一個空格,所以要更換應該是','。 (逗號和空格) –

+1

是的,我知道,我放在那裏它沒有來。我會編輯它。 –

+0

謝謝..工作正常。 (順便說一下,你可以用'$ str' ;-))替換'$ string'。 +1 – Shafizadeh

相關問題