Skip to content

Instantly share code, notes, and snippets.

@justinfay
Created May 19, 2016 09:46
Show Gist options
  • Save justinfay/7cf99315f7f2e0f2d1493ec333badbe2 to your computer and use it in GitHub Desktop.
Save justinfay/7cf99315f7f2e0f2d1493ec333badbe2 to your computer and use it in GitHub Desktop.
import re
odd_backslash = re.compile(r'((?<!\\)(\\\\)*\\(?!\\))')
def php_escape(value):
try:
return "'" + odd_backslash.sub(
r'\\\1', value.replace("'", r"\'")) + "'"
except AttributeError:
return str(value)
def to_php(mapping):
"""
Perform the equivalent of PHP's var_export to a python `dict`.
NOTE: Does not support nested arrays.
"""
php = "array (\n"
for key, value in mapping.iteritems():
php += ' ' + ' => '.join([
php_escape(key),
php_escape(value)
]) + ',\n'
php += ")"
return php
import unittest
class PHPTests(unittest.TestCase):
def test(self):
ONE_PHP = "array (\n '\\\\1' => '\\\\1',\n)"
ONE_PYTHON = {r'\1': r'\\1'}
self.assertEqual(ONE_PHP, to_php(ONE_PYTHON))
TWO_PHP = "array (\n 0 => 1,\n)"
TWO_PYTHON = {0: 1}
self.assertEqual(TWO_PHP, to_php(TWO_PYTHON))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment