Skip to content

Instantly share code, notes, and snippets.

@marcocesarato
Last active May 25, 2019 11:37
Show Gist options
  • Save marcocesarato/f64f1399d4768e93e3b6e11df9eeba35 to your computer and use it in GitHub Desktop.
Save marcocesarato/f64f1399d4768e93e3b6e11df9eeba35 to your computer and use it in GitHub Desktop.
Javascript function that parse php var_export
/**
* Parse php var_export
* @author Marco Cesarato <cesarato.developer@gmail.com>
* @param str
* @returns {*}
*/
function php2js(str) {
str = str.trim();
str = str.replace('<?php', '');
str = str.replace('?>', '');
str = str.replace(';', '');
str = str.replace('return ', '');
str = str.replace(/([0-9]+)\s+=>\s/g, '"$1" => ');
str = str.replace(/('|")([a-zA-Z0-9\_\-]+)('|")\s+=>\s/g, '"$2": ');
str = str.replace(/=>/g, ':');
str = str.replace(/array \(/g, '{');
str = str.replace(/\)/g, '}');
str = str.replace(/\s+/g, ' ');
str = str.replace(/,\s*}/g, '}');
str = str.replace(/'([^\r\n'""]*)'/g, '"$1"');
try {
str = JSON.parse(str);
} catch (e) {
return false;
}
return str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment