Книга: Fedora™ Unleashed, 2008 edition

Escape Sequences

Escape Sequences

Some characters cannot be typed, and yet you will almost certainly want to use some of them from time to time. For example, you might want to use an ASCII character for newline, but you can't type it. Instead, you need to use an escape sequence: n. Similarly, you can print a carriage return character with r. It's important to know both of these because on the Windows platform, you need to use rn to get a new line. If you do not plan to run your scripts anywhere else, you need not worry about this!

Going back to the first script we wrote, you will recall it printed 2010 because we added 10 + 10 and then 10 + 0. We can rewrite that using escape sequences, like this:

<?php
 $i = 10;
 $j = "10";
 $k = "Hello, world";
 echo $i + $j;
 echo "n";
 echo $i + $k;
 echo "n";
?>

This time PHP prints a new line after each of the numbers, making it obvious that the output is 20 and 10 rather than 2010. Note that the escape sequences must be used in double quotation marks because they do not work in single quotation marks.

Three common escape sequences are , which means "ignore the backslash"; ", which means "ignore the double quote"; and ', which means "ignore the single quote." This is important when strings include quotation marks inside them. If you had a string such as "Are you really Bill O'Reilly?", which has a single quotation mark in, this code would not work:

<?php
 echo 'Are you really Bill O'Reilly?';
?>

PHP would see the opening quotation mark, read all the way up to the O in O'Reilly, and then see the quotation mark following the O as being the end of the string. The Reilly? part would appear to be a fragment of text and would cause an error. You have two options here: You can either surround the string in double quotation marks or escape the single quotation mark with '.

If you choose the escaping route, it will look like this:

echo 'Are you really Bill O'Reilly?';

Although they are a clean solution for small text strings, you should be careful with overusing escape sequences. HTML is particularly full of quotation marks, and escaping them can get messy:

$mystring = "<img src="foo.png" alt="My picture" width="100" height="200" />";

In that situation, you are better off using single quotation marks to surround the text simply because it is a great deal easier on the eye!

Оглавление книги


Генерация: 3.508. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз