1

I need to add comma only at first and third spaces between 4 separated strings. I am using following regex but this is adding the , after each strings

<?php

$date = "Thursday November 3 2016";
$fdate = implode(", ", preg_split("/[\s]+/", $date));

echo $fdate;
?>

output:

Thursday, November, 3, 2016

which I need to get

Thursday, November 3, 2016

Can you please let me know how I can fix this?

Behseini
  • 6,066
  • 23
  • 78
  • 125

3 Answers3

7

You might be over-complicating things using a regex - how about using strtotime??

$date = "Thursday November 3 2016";
echo date('l, F j, Y',strtotime( $date ) );
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
0
$date = "Thursday November 3 2016";

$dateFormat = new DateTime($date);
echo date_format($dateFormat, 'l, F j, Y');
Gayan
  • 2,845
  • 7
  • 33
  • 60
0

Not that regex is the correct tool, but this is how I would have used regex for this problem:

$fdate = preg_replace("/(\w+) (\w+) (\d+) (\d+)/", "$1, $2 $3, $4", $date);
Andreas
  • 23,610
  • 6
  • 30
  • 62