2013-06-26 82 views
0

我有這樣的Preg替換字符串在PHP

Date,Impressions,Clicks,CTR,Orders,Orders/Click,EPC,Sales,Avg. Order,Baseline Commissions,Adjusted Commissions,Actual Commissions 01/03/2013,0,1,0,0,0,0,0,0,0,0,0 01/04/2013,0,1,0,0,0,0,0,0,0,0,0 01/05/2013,0,4,0,0,0,0,0,0,0,0,0 

我想在字符串中的每個「DATE」像這樣,01/03/2013

之前追加逗號我使用這個代碼,請幫我帶刺加上這個代碼,以獲得上述輸出

$pattern = '/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/'; 
$replacement = ','; 
$contents =preg_replace($pattern, $replacement, $contents); 

回答

1
$contents = "01/03/2013+otherthigns"; 
$pattern = '/([0-9]{2})\/[0-9]{2}\/[0-9]{4}/'; 
$replacement = ',$0'; 
$contents =preg_replace($pattern, $replacement, $contents); 
0

試試這個:

$pattern = '/([0-9]{2}\/[0-9]{2}\/[0-9]{4})/'; 
$replacement = ',$1'; 
$contents =preg_replace($pattern, $replacement, $contents); 

這會在每個日期之前添加逗號。

如果你想改變空格來逗號,然後做到這一點:

$pattern = '/\s([0-9]{2}\/[0-9]{2}\/[0-9]{4})/'; 
$replacement = ',$1'; 
$contents =preg_replace($pattern, $replacement, $contents);