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?

Drew
  • 75,699
  • 9
  • 109
  • 225
neochar
  • 13
  • 4
  • 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](https://www.gnu.org/software/emacs/manual/html_node/emacs/Save-Keyboard-Macro.html). `C-h r` and `C-h i` are your friends... – Drew Nov 22 '18 at 20:58

1 Answers1

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)))
xuchunyang
  • 14,302
  • 1
  • 18
  • 39