开发者

How to use regex to replace these words?

From:

citys["bj"] = {bj:"Beijing"};
citys["han"] = {haikou:"Haikou",hainan:"Hainan",sanya:"Sanya",wzs:"Wuzhishan"};

To:

"bj" => array("bj"=>"Beijing");
"han" => array("haikou"=>"Haikou","hainan"=>"Hainan","sanya"=>"Sanya","wzs"=>"Wuzhis开发者_如何学Pythonhan");

Thanks!


json_decode('{"bj":"Beijing"}', true);

But for this function worked fine you need to have proper json, with keys also surrounded with quotes.


You can solve this in two steps:

$temp = preg_replace('/(\w*?):("\w*?")/', '"$1"=>$2', $input);
$output = preg_replace('/citys\[("\w*?")\]\s*=\s*\{(.*?)\}/', '$1 => array($2)', $temp);

First you transform all haikou:"Haikou" into "haikou"=>"Haikou". Then you transform citys["bj"] = {...}; into "bj" => array(...);

The regexes then are:

  1. (\w*?):("\w*?")
  2. citys\[("\w*?")\]\s*=\s*{(.*?)}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜