Quickest way to write <?php echo ... ?>

Lars picture Lars · Feb 14, 2013 · Viewed 7.2k times · Source

There are many questions on stack exchange on whether or not you should use <?php echo ?> or <?= ?>.

I have decided to use <?php echo ?>, but am wondering if there is a good way to create a shortcut to save time writing this.

Currently I use a default setup of Sublime Text 2, with no plugins or anything installed, I'm not a "super user". But I do know that if I type php then press tab it outputs: <?php ?>.

Is there a way to get an echo inside this, and is it a good idea to do this? Has anyone done this already?

PS I should add, I don't always want the echo to appear, as I won't always be needing to echo something.

Answer

Jason picture Jason · Feb 14, 2013

You can bind a snippet to a keystroke.

<snippet>
    <content>
        <![CDATA[<?php echo ${1:What to echo}; ?>]]>
    </content>
    <description>Basic echo</description>
</snippet>

Save the above as echo.sublime-snippet in your Packages/User folder then edit Default (OS of your choice here).sublime-keymap and add

{ "keys": ["command+e"], "command": "insert_snippet", "args": {"name": "Packages/User/echo.sublime-snippet" } }

Swap out command-e for any key combination you want to use. Now, when you hit command & e Sublime will add in <?php echo ;?> for you and put the insertion cursor right before the ; for you - you can then start to type in what ever needs echoed.

You can also replace ${1:What to echo} with $TM_SELECTED_TEXT and Sublime will wrap the text you've selected with <?php echo & ;?> when you highlight text and hit command & e.