Behseini Behseini - 23 days ago 6
PHP Question

Adding Comma in Specific Spaces using Regex in PHP

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?

Answer

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