2

In PHP, when I write

$string="\thello world\t"
echo trim($string);

this outputs hello world. However, when I enter the same string in a HTML form input field and post to the server, the behavior changes.

echo trim($_POST["string"];

The above code outputs \thello world\t

What is the difference?

Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
Whiteley
  • 101
  • 1
  • 6

1 Answers1

1

This is because \t inside of double quotes is an escape sequence that is expanded to the literal tab character. However, when you type \t into an input field, it is posted as the literal characters \t.

In this example, this code.

echo trim($_POST["string"];

Is analogous to this code.

$string='\thello world\t'
echo trim($string);

Escape sequences are not expanded inside strings declared by single quotes.

If you need the functionality to expand the escape sequences from a submitted string, this question offers a few techniques.

Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
  • So, any input that comes from GET or POST is special character-safe? – Whiteley Mar 21 '15 at 17:43
  • @Whiteley Not necessarily, a user can still submit any arbitrary data, even if the input does not allow it. Escape sequences however, will not be expanded. If you are only concerned that a user might submit leading/trailing whitespace, `trim` is sufficient. – Alexander O'Mara Mar 21 '15 at 17:48
  • in this case, trim only removes space character, not special characters like \n or \t, am I right? – Whiteley Mar 21 '15 at 17:56
  • @Whiteley Space and other whitespace characters yes. `\n`, `\t` etc will literally be the characters entered and not transformed into whitespace. – Alexander O'Mara Mar 21 '15 at 18:06
  • @alexander-omara Normally, I use preg_replace('/\s+/', ' ', $string) on any input that is coming from $_POST to remove excess whitespace. I just want to able to keep if a user writes something "My name is newline(\n)". Based on your answer, I can continue to use this function and I don't need to worry about it right? – Whiteley Mar 21 '15 at 18:22
  • @alexander-omara Yes, but trim does not remove extra spaces inside the string (between individual words). – Whiteley Mar 21 '15 at 18:32
  • @Whiteley Right, if you want to strip internal whitespace, then your `preg_replace` solution is what you want. – Alexander O'Mara Mar 21 '15 at 19:02