• <code id="xuipv"></code>

    Embed literal text in PHP date format strings

    The tip offered in this post is actually documented in date page of the PHP manual but it’s one of those things I wasn’t aware of until seeing it in an example somewhere else just before posting this so I thought I would share it here. It’s how to embed some literal text in the format string for PHP’s date function.

    What I’ve done in the past – calling date() twice

    In the past if I’ve needed to have some date formatting, followed by some literal text and then more date formatting I’ve tended to do something like this, which is inefficient:

    1$foo = date('Y-m-d') . ' FOO ' . date('H-m-s');

    Call date once and escape each literal character

    To embed the literal text in the format string simply escape each literal character with a slash. Using the above example again, do this:

    1$foo = date('Y-m-d \F\O\O H-m-s');

    Now there’s only one call to the date() function.

    And here’s the situation where I used it this morning, setting the expires header for a webpage and being able to put the “GMT” part into the format string instead of concatenating it to the end:

    1header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time()+600 ), true);