简体   繁体   中英

how to use special expression using preg_match_all in php

I want to preg_match_all() this:

    if(isset($matches[1])){
        return $matches[1];
    }else{
        return false;
    }
}
$lines = file('jason.txt');
$i=0;
foreach ($lines as $line_num => $line) {
    $str_arr = getInbetweenStrings('"Vehicle":', ',"Buyer":', $line);
    echo '<pre>';
    print_r($str_arr);
}

If the string is:

"Vehicle": "1992 Macho Camry CE"

Here is the regex:

preg_match_all("/: \"?([\w ]+)/", $str, $matches,  PREG_PATTERN_ORDER);

Then call

print_r($matches);

Which will return:

Array
(
    [0] => Array
        (
            [0] => : "1992 Macho Camry CE
        )

    [1] => Array
        (
            [0] => 1992 Macho Camry CE
        )

)

To get the string, use:

$phrase = $matches[1];

edit: Because of the source data is a json string, use the json_decode function to convert all data in array:

$str = '[{"Vehicle": "1992 Macho Camry CE"}, {"Vehicle": "2017 OtherCar"}]';
$vehicles = json_decode($str, true);
print_r($vehicles);

Array
(
    [0] => Array
        (
            [Vehicle] => 1992 Macho Camry CE
        )

    [1] => Array
        (
            [Vehicle] => 2017 OtherCar
        )
)

Based on your comment you are parsing a json file.

In that case you should not use regexes or string functions. Instead you should parse the json file directly.

To get it all in a multi-dimensional array structure:

$array = json_decode(file_get_contents('path/to/file.json'), true);

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