PHP preg_split only inside double quotes

223 views Asked by At

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

3

There are 3 answers

0
Hamza Ali On BEST ANSWER

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 )

0
bobkorinek On

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.

0
Maik Lowrey On

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));