Home > Software engineering >  PHP preg_split only inside double quotes
PHP preg_split only inside double quotes

Time:03-14

How i can take the value only inside the double quotes with preg_split function

from this example string

$String = '["number","1","2470A K18-901","PEDAL ASSY, GEAR CHANGE","1","PCS","56500.00","0","56500","action"]'

into like this :

Array
(
    [0] => number
    [1] => 1
    [2] => 2470A K18-901
    [3] => PEDAL ASSY, GEAR CHANGE
    [4] => 1
    [5] => PCS
    [6] => 56500.00
    [7] => 0
    [8] => 56500
    [9] => action
)

or with another function to achieve that

CodePudding user response:

If you want to convert the string into array use json_decode:

   <?php
   $jsonobj = '["number","1","2470A K18-901","PEDAL ASSY, GEAR 
   CHANGE","1","PCS","56500.00","0","56500","action"]';

   print_r(json_decode($jsonobj));
   ?>

Output:

Array ( [0] => number [1] => 1 [2] => 2470A K18-901 [3] => PEDAL ASSY, GEAR CHANGE [4] => 1 [5] => PCS [6] => 56500.00 [7] => 0 [8] => 56500 [9] => action )

CodePudding user response:

That is a JSON String and you can convert it to an array by using the json_decode() function. https://www.php.net/manual/de/function.json-decode.php

<?php
$String = '["number","1","2470A K18-901","PEDAL ASSY, GEAR CHANGE","1","PCS","56500.00","0","56500","action"]';

print_r(json_decode($String));

CodePudding user response:

        <?php
//if $string is an array
        $String = ["number","1","2470A K18-901","PEDAL ASSY, GEAR CHANGE","1","PCS","56500.00","0","56500","action"];
            $newstring = ( str_replace('"', '', $String));
            echo "<pre>";
            print_r($newstring);
            echo "</pre>";
        ?>

<?php
//if $string is a string
$String = '["number","1","2470A K18-901","PEDAL ASSY, GEAR CHANGE","1","PCS","56500.00","0","56500","action"]';
    $newstring = (str_replace('"', '', $String));
    $newstring1 = explode("," , $newstring);
    echo "<pre>";
    print_r($newstring1);
    echo "</pre>";
 
?>
    
    output will be :-
    Array
    (
        [0] => number
        [1] => 1
        [2] => 2470A K18-901
        [3] => PEDAL ASSY, GEAR CHANGE
        [4] => 1
        [5] => PCS
        [6] => 56500.00
        [7] => 0
        [8] => 56500
        [9] => action
    )

CodePudding user response:

If the value that you wish to be splitted is actually type of string (as represented in your question), you can use preg_match_all instead (with preg_match_all it's basically one line to match all the neccessery values; with preg_split you'd have to trim the brackets around the values).

<?php

$String = '["number","1","2470A K18-901","PEDAL ASSY, GEAR CHANGE","1","PCS","56500.00","0","56500","action"]';
preg_match_all('/(?<=,"|\[")[^"] ?(?=")/', $String, $Match);
$Result = $Match[0];

var_dump($Result);

PS: This solution assumes that the values inside the array doesn't have any escaped quotes.

  • Related