Cynial
Cynial

Reputation: 680

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"=>"Wuzhishan");

Thanks!

Upvotes: 1

Views: 97

Answers (2)

Staffan Nöteberg
Staffan Nöteberg

Reputation: 4145

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*{(.*?)}

Upvotes: 1

zerkms
zerkms

Reputation: 254886

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

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

Upvotes: 4

Related Questions