Search code examples
phparrayscsvstr-replacequoting

How to apply double quotes to each value in a comma-space delimited string?


I want to add double quotes of my every array.

Original value is:

192.168.183.2, 192.168.183.28

The current result is:

"192.168.183.2, 192.168.183.28"

What I want is:

"192.168.183.2", "192.168.183.28"

and here is my code:

$allowedIP = array($dScheduler['ALLOWED_IP_ADDRESS']);
echo $newarray='"'.implode('","', $allowedIP).'"';

Solution

  • Your input value is a string, so handle it with just one string function call (str_replace()):

    Code: (Demo)

    $dScheduler['ALLOWED_IP_ADDRESS']='192.168.183.2, 192.168.183.28';  // your input string
    $wrapped='"'.str_replace(', ','", "',$dScheduler['ALLOWED_IP_ADDRESS']).'"';
    echo $wrapped;
    
    echo "\n\n";
    // if you want an array:
    $array=explode(', ',$wrapped);  // generate result array
    foreach($array as $v){
        echo "$v\n";
    }
    

    The value delimiter in your input string is: ,, so you just need to change it to ", " and wrap the entire string in " as well. Then you simply explode on the commas to generate your desired array of elements.

    Output:

    "192.168.183.2", "192.168.183.28"
    
    "192.168.183.2"
    "192.168.183.28"