Amit Rathore
Amit Rathore

Reputation: 13

How to create with comma separated with single qoutes list from array in PHP?

This is my question that i have this type of string

04/19/2017, 04/20/2017, 04/26/2017, 04/28/2017

i want to output as like below output

'04/19/2017','04/20/2017','04/26/2017','04/28/2017'

Upvotes: 1

Views: 51

Answers (4)

Jagadeesh Harshan
Jagadeesh Harshan

Reputation: 16

Without using explode and implode

$string = "04/19/2017, 04/20/2017, 04/26/2017, 04/28/2017"; $string = "'".str_replace(", ","','",$string)."'";

Upvotes: 0

Pedro Lobito
Pedro Lobito

Reputation: 98871

For your specific example, you can use:

$result = preg_replace('%([\d/]+)%sim', '"\1"', $string);

Output:

"04/19/2017", "04/20/2017", "04/26/2017", "04/28/2017"

Regex Explanation:

([\d/]+)

Match the regex below and capture its match into backreference number 1 «([\d/]+)»
   Match a single character present in the list below «[\d/]+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
      A “digit” (any decimal number in any Unicode script) «\d»
      The literal character “/” «/»

"\1"

Insert the character “"” literally «"»
Insert the text that was last matched by capturing group number 1 «\1»
Insert the character “"” literally «"»

Demo

Upvotes: 0

David James Haw
David James Haw

Reputation: 11

<?php
// dates in a string
$data = '04/19/2017, 04/20/2017, 04/26/2017, 04/28/2017';

// break them apart into array elements where the , is
$dates = explode(',', $data);


/* You then have array of dates you can use/display how you want, ie:: */
foreach($dates as $date){
    echo $date. '<br/ >';
}

/* OR select single date */
echo $dates[0];

Upvotes: 1

Autista_z
Autista_z

Reputation: 2541

$string = "04/19/2017, 04/20/2017, 04/26/2017, 04/28/2017";
$array = explode(", ", $string);
$string = "'".implode("','", $array)."'";

Upvotes: 0

Related Questions