1

Say I have PHP array like this: $arr = ['one', 'two', 'three']; and I want to convert it to

$arr = [
    'one',
    'two',
    'three'
];

real quick.

Is there any ready to use soluions?

  • Define and use a keyboard macro. Just record your manual edits and replay. Use keys that move syntactically, e.g., search for a comma or whatever. – Drew Nov 22 '18 at 16:03
  • @Drew, can I record macro to use it after I close and open emacs again? – neochar Nov 22 '18 at 19:42
  • Yes, of course. See the Emacs manual, node Save Keyboard Macro. C-h r and C-h i are your friends... – Drew Nov 22 '18 at 20:58
1

Don't know about PHP. You can try to search for PHP code formatters and see if it has such function.

Here is a simple solution using regular expression. It works for your particular example at least.

(defun your-php-array-multiline (b e)
  "Turn oneline php array to multiline."
  (interactive "*r")
  (insert
   (replace-regexp-in-string
    (rx (in "[,]"))
    (lambda (s)
      (pcase (match-string 0 s)
        ("[" "[\n")
        ("," ",\n")
        ("]" "\n]")))
    (delete-and-extract-region b e)))
  (indent-region b (point)))

In case you want to convert the multiline array back:

(defun your-php-array-oneline (b e)
  "Turn multiline php array to oneline."
  (interactive "*r")
  (insert
   (replace-regexp-in-string
    "\n\s*"
    ""
    (delete-and-extract-region b e))))

and toggle between oneline and multiline

(defun your-php-array-toggle (b e)
  "Toggle php array between oneline and multiline."
  (interactive "*r")
  (if (string-match-p "\n" (buffer-substring b e))
      (your-php-array-oneline b e)
    (your-php-array-multiline b e)))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.