1

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.

2
  • How are you getting $string? Commented Dec 26, 2013 at 20:08
  • 2
    What is wrong with json_decode? works fine for me: codepad.viper-7.com/iT2T8G You could then just loop over the array and explode on :. Commented Dec 26, 2013 at 20:14

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

You won't believe me when I tell you I tried this already, but for some reason it works now, so you have my thanks.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.