Skip to content

Instantly share code, notes, and snippets.

@afanasy
Last active November 18, 2015 15:03
Show Gist options
  • Save afanasy/19748c0277f8b3fd4744 to your computer and use it in GitHub Desktop.
Save afanasy/19748c0277f8b3fd4744 to your computer and use it in GitHub Desktop.
Regexps helper to convert php code to javascript
php2js: function (file, out, done) {
fs.readFile(file, {encoding: 'utf8'}, function (err, data) {
var replace = [
{in: /;\n/, out: '\n'},
{in: /->/, out: '.'},
{in: /\$([a-z0-9_]+)/, out: '$1'},
{in: /([a-z0-9_]+?)\['([^\]]+?)'\]/, out: '$1.$2'},
{in: / \. /, out: ' + '},
{in: / \.= /, out: ' += '},
{in: /foreach \(([a-z0-9_.]+?) as &?([a-z0-9_.]+?)\)/, out: '_.each($1, function ($2)'},
{in: /foreach \(([a-z0-9_.]+?) as ([a-z0-9_.]+?) => ([a-z0-9_.]+?)\)/, out: '_.each($1, function ($3, $2)'},
{in: /'([a-z0-9_.]+?)' => ([^\] ]+)/, out: '$1: $2'},
{in: /([^ \]]+?) => ([^ \]]+?)/, out: '$1: $2'},
{in: /\(int\)/, out: '+'},
{in: /ucfirst/, out: 'api.ucfirst'},
{in: /isset\((.+?)\)/, out: '!_.isUndefined($1)'},
{in: /count\((.+?)\)/, out: '$1.length'},
{in: /strlen\((.+?)\)/, out: '$1.length'},
{in: /strtolower\((.+?)\)/, out: '$1.toLowerCase()'},
{in: /substr\((.+?), (.+?)\)/, out: '$1.substr($2)'},
{in: /json_encode\((.+?)\)/, out: 'JSON.stringify($1)'},
{in: /json_decode\((.+?)(, true)?\)/, out: 'JSON.parse($1)'},
{in: /unset\((.+?)\)/, out: 'delete $1'}
]
_.each(replace, function (value) {
data = data.replace(new RegExp(value.in.source, 'ig'), value.out)
})
fs.writeFile(out, data, function () {
console.log(data.length)
done()
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment