Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't the "\t" escaping this PHP date format?

Tags:

date

php

escaping

Here's the date. Everything is being escaped but the t in "\a\t". Anybody know why?

date("M m\, Y \a\t g\:ia", $s->post_date);
like image 991
Timothy Owen Avatar asked Dec 21 '22 00:12

Timothy Owen


1 Answers

"\t" is a escape sequence for the horizontal tab character.

Use '\t' or "\\t"

Single-quoted strings interpret \ literally, which I'd recommend for your use case. Otherwise you have to escape the \ character to have it interpreted literally.

In PHP's case, the \ preceding an invalid escape sequence inside a double-quoted string also gets interpreted literally. I'd rather avoid this behavior, following the principle of least surprise.

ps. (thanks to @IMSoP) There are two cases where \s are not interpreted literally inside single-quoted strings:

  • Doubling backslashes is still possible but optional. E.g.: '\\hi' === '\hi'
  • The string delimiter character must be escaped inside of a string literal. E.g.: '\'' === "'"

Still, single-quoted strings are less surprising in that \n, \r, \t, \v, \040 and similar result in the actual sequence of characters inside of the string literal instead of these being interpreted as escape sequences.

Doubling all backslashes that must be interpreted literally is also a sturdy option that works with both double and single quoted strings as well.

like image 183
Fabrício Matté Avatar answered Jan 03 '23 02:01

Fabrício Matté