简体   繁体   English

从PHP中的JSON字符串中提取正则表达式

[英]Regular expression extraction from JSON string in PHP

I have a string in PHP which could look similar to the following: 我在PHP中有一个字符串,看起来可能类似于以下内容:

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

It is generated from a JSON Array. 它是从JSON数组生成的。 I need to write a regular expression to separate the JSON elements into a PHP array. 我需要编写一个正则表达式以将JSON元素分离为一个PHP数组。 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. 我最好的办法是将JSON数组解析为PHP数组。 So as an alternate (and preferred) solution, a way to parse the JSON array into a PHP array would be spectacular. 因此,作为一种替代的(也是首选的)解决方案,一种将JSON数组解析为PHP数组的方法将非常壮观。 I have already tried to json_decode the string, but it always yields NULL . 我已经尝试过对字符串进行json_decode了,但是它总是产生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. 编辑:出于好奇,当我直接从输出中复制字符串而不进行过滤和json_decode ,它将完美地转换为PHP数组。

If it is a valid JSON string, try this (the solution is safer than using regexens): 如果它是有效的JSON字符串,请尝试以下方法(该解决方案比使用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 在这里,看看这个: http : //codepad.viper-7.com/4JVAV8

As Jonathan Kuhn confirmed, json_decode works fine. 正如乔纳森·库恩(Jonathan Kuhn)确认的那样,json_decode可以正常工作。 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
        )
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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