繁体   English   中英

如何在php中使用preg_match_all使用特殊表达式

[英]how to use special expression using preg_match_all in php

我想preg_match_all()这个:

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

如果字符串是:

"Vehicle": "1992 Macho Camry CE"

这是正则表达式:

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

然后打电话

print_r($matches);

哪个将返回:

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

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

)

要获取字符串,请使用:

$phrase = $matches[1];

编辑:由于源数据是json字符串,使用json_decode函数转换数组中的所有数据:

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

根据您的评论,您正在解析json文件。

在这种情况下,您不应该使用正则表达式或字符串函数。 相反,你应该直接解析json文件。

要在多维数组结构中完成所有操作:

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

暂无
暂无

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

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