Reformat String in PHP To Add Double Quotes and Backslash

Viewed 58

I am hoping someone can help me. I have a variable in PHP that I need to use in a bash script. That string in the variable needs to be transformed to a specific format to wrap every word in the string in double quote and backslash.

Here is it specifically:

$raw = "amazon,facebook,reddit";

The output of the desired function needs to look like this:

\"amazon\",\"facebook\",\"reddit\"

Obviously the $raw variable could hold more or less words separated by comma.

The best I could do using str_replace is this:

$trfm = '"' . str_replace(",", "\",\"", $raw) . '"';

echo $trfm;

"amazon","facebook","reddit" 

so I need to figure out how to add the backslashes.

Thanks

2 Answers

You could use array_walk() for this.

// Input
$raw = "amazon,facebook,reddit";

// Turn items into an array, separated by commas
$items = explode(",", $raw); // ['amazon', 'facebook', 'reddit']

// Walk over each item in the array, and transform it
array_walk($items, function (&$value) {
  $value = '\"' . $value . '\"'; 
});

// Output: \"amazon\",\"facebook\",\"reddit\"
echo implode(",", $items);

For completeness, if you didn't want to split this into an array, and wanted to go with your approach of swapping commas with the backslashes, you could do the following. Note the use of double slashes, which are used by double quotes, to avoid having to escape these, you could use single quotes instead.

// Input
$raw = "amazon,facebook,reddit";

// Notice the double backslash below: \\
echo "\\\"" . str_replace(",", "\\\",\"", $raw) . "\\\"";

// Notice the single quotes and the lack of escaping with double backslash:
echo '\"' . str_replace(",", '\",\"', $raw) . '\"';

Hi this would be my solution:

    $raw = "amazon,facebook,reddit";
    $raw_arr = explode(',',$raw); 

    $output = ''; 

    for($i = 0; $i < sizeof($raw_arr); $i++) 
    {

        $output = $output.'\"'.$raw_arr[$i].'\"';
        
        // Check if we need to add , --> don't add if it is last element
        if(! ($i == sizeof($raw_arr) -1) )
        {
            $output = $output.','; 
        }
 
    }

    echo $output;
Related