如何使用正则表达式替换这些单词?

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!

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*{(.*?)}
json_decode('{"bj":"Beijing"}', true);

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