Last active
May 25, 2019 11:37
-
-
Save marcocesarato/f64f1399d4768e93e3b6e11df9eeba35 to your computer and use it in GitHub Desktop.
Javascript function that parse php var_export
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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