PHP

Strings

A string of characters-a string-is probably the most commonly used data type when developing scripts, and PHP provides a large library of string functions to help transform, manipulate, and otherwise manage strings. We introduced PHP strings earlier, in Section 2.1.1. Here, we examine string literals in more detail and describe some of the useful string functions PHP provides.

String Literals

As already shown in previous examples, enclosing characters in single quotes or double quotes can create a string literal. Single-quoted strings are the simplest form of string literal; double-quoted strings are parsed to substitute variable names with the variable values and allow characters to be encoded using escape sequences. Single-quoted strings don't support all the escape sequences, only \' to include a single quote and \\ to include a backslash.

Tab, newline, and carriage-return characters can be included in a double-quoted string using the escape sequences \t, \n, and \r, respectively. To include a backslash, a dollar sign, or a double quote in a double-quoted string, use the escape sequences \\, \$, or \".

Other control characters and characters with the most significant bit set can be included using escaped octal or hexadecimal sequences. For example, to include the umlauted character , the octal sequence \366 or the hexadecimal sequence \xf6 are used:

//Print a string that includes a lowercase
//o with the umlaut mark
echo "See you at the G\xf6teborg Film Festival";

PHP uses eight-bit characters in string values, so the range of characters that can be represented is \000 to \377 in octal notation or \x00 to \xff in hexadecimal notation.

Unlike many other languages, PHP allows newline characters to be included directly in a string literal. The following example show the variable $var assigned with a string that contains a newline character:

// This is Ok. $var contains a newline character
$var = 'The quick brown fox
        jumps over the lazy dog';

This feature is used in later chapters to construct SQL statements that are readable in the source code, for example:

$query = "SELECT max(order_id)
          FROM orders
          WHERE cust_id = $custID";

Other control characters, such as tabs and carriage returns, and characters with the most significant bit set-those in the range \x80 to \xff-can also be directly entered into a string literal. We recommend that escape sequences be used in practice to aid readability and portability of source files.

by BrainBellupdated
Advertisement: