Manoaj J Rathore
Manoaj J Rathore

Reputation: 127

Prepend a comma to all d/m/Y date expressions in text containing comma-separated values

I have a string with CSV text like this:

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 

I am trying to append comma before each "DATE" in string like this ,01/03/2013

I am using this code please help me to add on this code to get above output

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

Upvotes: 0

Views: 89

Answers (2)

user1064590
user1064590

Reputation:

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

Upvotes: 1

Fracsi
Fracsi

Reputation: 2314

Try this:

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

This adds comma before every date.

If you want to change the whitespace to comma, then do this:

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

Upvotes: 0

Related Questions