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
  • 5,746
  • 20
  • 67
  • 114

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
  • 30,177
  • 5
  • 29
  • 43
0
$date = "Thursday November 3 2016";

$dateFormat = new DateTime($date);
echo date_format($dateFormat, 'l, F j, Y');
Mak
  • 2,765
  • 7
  • 31
  • 56
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,304
  • 5
  • 28
  • 61