Friday, July 4, 2014

Escape Sequence in PHP

Escape sequence in PHP means preventing PHP from ending strings early or making sure you have the correct string information returned.

For example:

<?php

    $string='Rita's new house';
    echo $string;
?>

Here, there is no any syntax error. We have just written a normal code. But while running this code it will give an error message.

Why?

Because there is three single quote marks in the above statement. PHP gets confused since it doesn't know what is the string.

To solve such problem, you can use double quotes on the outside. Let's write the above code again.

<?php
    $string="Rita's new house";
    echo $string;

?>

Well it will run perfectly but if you don't want to use double quote outside the single quote then you can escape the apostrophe. You can use excape it by a character by typing a "slash"(\) before it like below:

<?php

    $string='Rita\'s new house';
    echo $string;
?>

Now run this, it should run perfectly fine.

So now you should know the concept about escape sequence, it is used to print the output where PHP have special meaning of.

Below are some other use of backslash as escape sequence.

\" -> It prints the next character as a double quote, not a string closer
\' -> It prints the next character as a single quote, not a string closer
\n -> It prints a new line character
\t -> It prints a tab character
\$ -> It prints the next character as a dollar sign but not as a part of a variable

\\ -> It prints the next character as a backslash but not as a escape sequence character

No comments:

Post a Comment