Search code examples
phppostescapingspecial-charactersforms

php and special characters


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?


Solution

  • 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.