2017-02-24 26 views
1

我想preg_match_all()这个:如何使用特殊的表达在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); 
} 
+1

的字符串是'“车辆”:“1992年凯美瑞的强壮男子CE”'? – Mohammad

+0

展示你如何使用'getInbetweenStrings'功能 – RomanPerekhrest

+0

这是一个数组 “QuoteRequestId” 中:343816132, \t \t “车辆”: “1992年凯美瑞强壮男子CE”, \t \t “买家”: “卡罗来纳州车身”, –

回答

0

如果字符串:

"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 
     ) 
) 
+0

mmm最初是哪种类型的数据? JSON?串?或者已经是数组? – user2342558

+0

在这种情况下,我建议你使用'json_decode'来创建一个包含所有元素的数组。 – user2342558

+0

查看我的最后编辑:) – user2342558

0

根据您的评论你解析一个json文件。

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

为了得到这一切在一个多维数组结构:

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

我已经做到了,但它是以txt格式 –

+0

让我发送你的文件。 –

+0

@BriguDash json是人类可读的文本。只要文本文件的内容为一个有效的json字符串,你可以解析它就好了。 – jeroen

相关问题