Home > Net >  convert double quote array values to single quote in php
convert double quote array values to single quote in php

Time:08-11

    $newArray=[];
    $arr=["1660109707.jpg","1660109715.png","1660201812.jpg","1660201843.jpg","1660208040.jpg"];
    foreach($arr as $ar)
    {
        $newArray[]=str_replace('"', "'", trim($ar,'"')); 

    }
    $newArray=json_encode($newArray);
    dd($newArray);

I tried the above code. but it still outputs "["1660109707.jpg","1660109715.png","1660201812.jpg","1660201843.jpg","1660208416.jpg"]"

espected

['1660109707.jpg','1660109715.png','1660201812.jpg','1660201843.jpg','1660208416.jpg']

CodePudding user response:

To get that expected result, you can replace the double quotes after the json encoding

$arr = ["1660109707.jpg","1660109715.png","1660201812.jpg","1660201843.jpg","1660208040.jpg"];
$jsonText=json_encode($arr);

//$jsonText = str_replace("'", "\'", $jsonText); //this is to replace the "inside text" quotes to escaped ones.It is not needed in your example
$notJsonText = str_replace("\"", "'", $jsonText);
dd($notJsonText);

Keep in mind that the resulting text in no longer a valid json format since json requires that string be encapsulated by double quotes "

By the way, these two arrays are equivalent

$arr1 = ["1660109707.jpg"];
$arr2 = ['1660109707.jpg'];

dd($arr1 === $arr2); //true

CodePudding user response:

First of all you dont have an array. That is a string. To convert this string to an array you can use the explode function (https://www.php.net/manual/de/function.explode.php). Then you can iterate the array an use the str_replace function the replace the double quotes.

<?php   $string='["1660109707.jpg","1660109715.png","1660201812.jpg","1660201843.jpg","1660208040.jpg"]';
$arr = [];
$newArray=[];

$string = str_replace('[', "", $string);
$string = str_replace(']', "", $string);
$arr = explode(",", $string);

// first print
print_r($arr);
foreach($arr as $ar)
{
    $newArray[]=str_replace('"', "'", trim($ar,'"')); 
}

// second print
print_r($newArray);

// get type of the first item from the new array.
echo getType($newArray[0]);

Output

Array
(
    [0] => "1660109707.jpg"
    [1] => "1660109715.png"
    [2] => "1660201812.jpg"
    [3] => "1660201843.jpg"
    [4] => "1660208040.jpg"
)
Array
(
    [0] => 1660109707.jpg
    [1] => 1660109715.png
    [2] => 1660201812.jpg
    [3] => 1660201843.jpg
    [4] => 1660208040.jpg
)
string

Note However, based on the question, I suspect that the problem is different from the double quotes.

  • Related