简体   繁体   中英

Regular expression extraction from JSON string in PHP

I have a string in PHP which could look similar to the following:

$string = '"["1000: Person One","1001: Person 2","1002: Person Three"]"';

It is generated from a JSON Array. I need to write a regular expression to separate the JSON elements into a PHP array. I need to pull just the numbers before each colon out. I have tried the following code, with no success:

preg_match_all('/\"[^:]*:/',$string,$target_array); //No Success
preg_match_all(/\"\d*:/,$string,$target_array); //No Success

What I need is a regex which can pull any characters between a " and a : .

Of course, this leaves problems if a person's name happens to include a similar pattern. The best thing I could do would be to parse the JSON array into a PHP array. So as an alternate (and preferred) solution, a way to parse the JSON array into a PHP array would be spectacular. I have already tried to json_decode the string, but it always yields NULL .

Edit: As a curiosity, when I copy the string directly from output with no filtering and json_decode that, it converts to a PHP array perfectly.

If it is a valid JSON string, try this (the solution is safer than using regexens):

$string = '["1000: Person One","1001: Person 2","1002: Person Three"]';
$arr = json_decode($string);
$keys = array();
foreach ($arr as $value) {
  $keys[] = (int)current(explode(":", $value, 2));
}
print_r($keys); // $keys contains the numbers you want.

// output:
//  Array
// (
//    [0] => 1000
//    [1] => 1001
//    [2] => 1002
// )

Here, have a look at this: http://codepad.viper-7.com/4JVAV8

As Jonathan Kuhn confirmed, json_decode works fine. but you can use regular expressions too:

$string = '["1000: Person One","1001: Person 2","1002: Person Three"]';
preg_match_all('/"(.*?):\s*([^"]+)"/', $string, $matches);
print_r($matches);

Output :

Array
(
    [0] => Array
        (
            [0] => "1000: Person One"
            [1] => "1001: Person 2"
            [2] => "1002: Person Three"
        )

    [1] => Array
        (
            [0] => 1000
            [1] => 1001
            [2] => 1002
        )

    [2] => Array
        (
            [0] => Person One
            [1] => Person 2
            [2] => Person Three
        )
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM