开发者

How to do regex in following Data using PHP

// [ { "id": "715320" ,"t" : "500268" ,"e" : "BOM" ,"l" : "15.55" ,"l_cur" : "Rs.15.55" 

,"ltt":"3:59PM IST" ,"lt" : "Sep 9, 3:59PM IST" ,"c" : "+1.69开发者_开发知识库" ,"cp" : "12.19"

,"ccol" : "chg" } ]

I need to Get each with name and assign the value to each

Like

$id=715320;

$e=BOM;

from above data, how can i do that?


As that's JSON encoded data, you can use json_decode rather than a regex - this is far more reliable (be sure to remove the leading \\ as that's a comment rather than JSON).

To then get the data into named variables:

$array = json_decode($string, true);
foreach ($array as $k => $v){
    $$k = $v;
}

This will result in id, t etc (which are now keys in $array) being set as their own variables like $id, $t .

edit: as aularon notes, you can also use the extract method to move the array keys to the global scope.


Your string totally looks like a JSon data. You should use the JSon methods to parse the content.


If your really want to use regexes you can do this :

<?php
$yourString = '// [ { "id": "715320" ,"t" : "500268" ,"e" : "BOM" ,"l" : "15.55" ,"l_cur" : "Rs.15.55" 
,"ltt":"3:59PM IST" ,"lt" : "Sep 9, 3:59PM IST" ,"c" : "+1.69" ,"cp" : "12.19" 
,"ccol" : "chg" } ] ';

preg_match_all("/\"(.+?)\"\s*:\s*\"(.+?)\"/", $yourString, $matches, PREG_SET_ORDER);

foreach($matches as $match){
    $resultArray[$match[1]] = $match[2];
}

print_r($resultArray);

?>

Code on ideone


Is used an array instead of variables in this code, but if you do really want to use variables such as $e which is a really really bad idea, you can use variable variables.

You replace the foreach content by this : ${$match[1]} = $match[2];


Resources :

  • php.net json_decode()

On the same topic :

  • Help with consuming JSON feed with PHP & json_decode


You don't need regular expressions, above is a JSON object notation, you need to do php json_decode on it, get the values, which will be an associative array:

$str='[ { "id": "715320" ,"t" : "500268" ,"e" : "BOM" ,"l" : "15.55" ,"l_cur" : "Rs.15.55" 
,"ltt":"3:59PM IST" ,"lt" : "Sep 9, 3:59PM IST" ,"c" : "+1.69" ,"cp" : "12.19" 
,"ccol" : "chg" } ] ';

$data=json_decode($str, true); //true to get the data as associative arrays rather than objects.
$data = $data[0];//since it's an object inside an array

from now on it's recommended keeping this as an associative array, and access objects using array accessors:

$id = $data['id'];

PHP's extract function can be used to extract those values into current context, but that is dangerous, sticking to the accessing the array directly is a better idea.


Isn't that simply JSON? Then take a look at json_decode. Or is there a reason you need to do this with a Regex?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜