HiDayurie Dave
HiDayurie Dave

Reputation: 1807

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).'"';

Upvotes: 1

Views: 632

Answers (5)

mickmackusa
mickmackusa

Reputation: 48100

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"

Upvotes: 1

Raphael
Raphael

Reputation: 11

    $allowedIP = array('192.168.183.2, 192.168.183.28');
    $new= implode($allowedIP);
    $fl=','; 

    foreach (explode(',',$new) as $v){ 
      echo '"'.$v.'"'.$fl; 
           $fl=''; 
        }; 

Upvotes: -1

Angger
Angger

Reputation: 805

Try This,

$arr = ["192.168.183.2", "192.168.183.28"];

$imp = '"'.implode('", "', $arr).'"'; // to string with double quote

$exp = explode(',', $imp); // to array with double quote

echo $im;

print_r($exp);

Upvotes: 0

Rob Ruchte
Rob Ruchte

Reputation: 3707

You can use array_map

<?php
$allowedIP = array('192.168.183.2, 192.168.183.28');

$arrAllowedIP = explode(',', $allowedIP[0]);

$quotedIP = array_map(function($val)
{
    return '"'.trim($val).'"';
}, $arrAllowedIP);

Upvotes: 0

Source
Source

Reputation: 1021

Do it through a loop:

$new_array = array();
foreach($array as $a) {
   $new_array[] = '"'.$a.'"';
}

It will create a new array with ", around each element.

Upvotes: 1

Related Questions