home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam    

Web Database Applications with PHP \& MySQLWeb Database Applications with PHP \& MySQLSearch this book

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

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

2.6.2. Printing and Formatting Strings

Earlier we presented the basic method for outputting text—with echo and print—and the functions print_r( ) and var_dump( ), which can determine the contents of variables during debugging.

PHP provides several other functions that allow more complex and controlled formatting of strings. Creating formatted output with sprintf( ) and printf( )

Sometimes more complex output is required than can be produced with echo or print. For example, a floating-point value such as 3.14159 might need to be truncated to 3.14 as it is output. For complex formatting, the sprintf( ) or printf( ) functions are useful:

string sprintf (string format [, mixed args...]) 
integer printf (string format [, mixed args...])

The operation of these functions is modeled on the identical C programming language functions, and both expect a string with optional conversion specifications, followed by variables or values as arguments to match any formatting conversions. The difference between sprintf( ) and printf( ) is that the output of printf( ) goes directly to the output buffer PHP uses to build a HTTP response, whereas the output of sprintf( ) is returned as a string.

Consider an example printf statement:

printf("Result: %.2f\n", $variable);

The format string Result: %.2f\n is the first parameter to the printf statement. Strings like Result: are output the same as with echo or print. The %.2f component is a conversion specification:

  • All conversion specifications begin with a % character.

  • The f indicates how the type of value should be interpreted. The f means the value should be interpreted as a floating-point number, for example, 3.14159 or 128.23765. Other possibilities include b, c, d, and s, where b means binary, c means a single character, d means integer, and s means string.

  • The .2 is an optional width specifier. In this example, .2 means two decimal places, so the overall result of %.2f is that a floating-point number with two decimal places is output. A specifier %5.3f means that the minimum width of the number before the decimal point should be five (by default, the output is padded on the left with space characters and right-aligned), and three digits should occur after the decimal point (by default, the output on the right of the decimal point is padded on the right with zeros).

In the example, the value that is actually output using the formatting string %.2f is the value of the second parameter to the printf function—the variable $variable.

To illustrate other uses of printf, consider the examples in Example 2-5.

2.6.4. Finding and Extracting Substrings

PHP provides several simple and efficient functions that can identify and extract specific substrings of a string. Finding the position of a substring

The strpos( ) function returns the index of the first occurring substring needle in the string haystack:

integer strpos(string haystack, string needle [, integer offset])

When called with two arguments, the search for the substring needle is from the start of the string haystack at position zero. When called with three arguments, the search occurs from the index offset into the haystack. The following examples show how strpos( ) works:

$var = "To be or not to be";

print strpos($var, "T");     // 0
print strpos($var, "be");    // 3

// Start searching from the 5th character in $var
print strpos($var, "be", 4); // 16

The strrpos( ) function returns the index of the last occurrence of the single character needle in the string haystack:

integer strrpos(string haystack, string needle)

Unlike strpos( ), strrpos( ) searches for only a single character, and only the first character of the needle string is used. The following examples show how strrpos( ) works:

$var = "To be or not to be";

// Prints 13: the last occurrence of "t"
print strrpos($var, "t");

// Prints 0: Only searches for "T" which 
// is found at position zero
print strrpos($var, "Tap"); 

// False: "Z" does not occur in the subject
onlyprint strrpos($var, "Zoo"); 

If the substring needle isn't found by strpos( ) or strrpos( ), both functions return false. The is-identical operator === should be used when testing the returned value from these functions against false. If the substring needle is found at the start of the string haystack, the index returned is zero and is interpreted as false if used as a Boolean value. Extracting multiple values from a string

PHP provides the explode( ) and implode( ) functions, which convert strings to arrays and back to strings:

array explode(string separator, string subject [, integer limit])
string implode(string glue, array pieces)

The explode( ) function returns an array of strings created by breaking the subject string at each occurrence of the separator string. The optional integer limit determines the maximum number of elements in the resulting array; when the limit is met, the last element in the array is the remaining unbroken subject string. The implode( ) function returns a string created by joining each element in the array pieces, inserting the string glue between each piece. The following example shows both the implode( ) and explode( ) functions:

$guestList = "Sam Meg Sarah Ben Jess May Adam";
$name = "Fred";

// Check if $name is in the $guestList
if (strpos($guestList, $name) === false)
  $guestArray = explode(" ", $guestList);
  echo "Sorry '$name' is not on the guest list.\n";
  echo "Guest list: " . implode(", ", $guestArray)

When the string $name isn't found in the string $guestList using strpos( ), the fragment of code prints a message to indicate that $name isn't contained in the list. The message includes a sorted list of comma-separated names: explode( ) creates an array of guest names that is sorted and then, using implode( ), is converted back into a string with each name separated by a comma and a space. The example prints:

Sorry 'Fred' is not on the guest list.
Guest list: Adam, Ben, Jess, May, Meg, Sam, Sarah 

2.6.5. Replacing Characters and Substrings

PHP provides several simple functions that can replace specific substrings or characters in a string with other strings or characters. In the next section we discuss powerful tools for finding and replacing complex patterns of characters. The functions described in this section, however, are more efficient than regular expressions and are often the better choice when searching and replacing strings. Replacing substrings

The substr_replace( ) function replaces a substring identified by an index with a replacement string:

string substr_replace(string source, string replace, int start [, int length])

Returns a copy of the source string with the characters from the position start to the end of the string replaced with the replace string. If the optional length is supplied, only length characters are replaced. The following examples show how substr_replace( ) works:

$var = "abcdefghij";

// prints "abcDEF";
echo substr_replace($var, "DEF", 3);

// prints "abcDEFghij";
echo substr_replace($var, "DEF", 3, 3);

// prints "abcDEFdefghij";
echo substr_replace($var, "DEF", 3, 0);

The str_replace( ) function returns a string created by replacing occurrences of the string search in subject with the string replace:

mixed str_replace(mixed search, mixed replace, mixed subject)

In the following example, the subject string, "old-age for the old", is printed with both occurrences of old replaced with new:

$var = "old-age for the old.";

echo str_replace("old", "new", $var);

The result is:

new-age for the new.

Since PHP Version 4.0.5, str_replace( ) allows an array of search strings and a corresponding array of replacement strings to be passed as parameters. The following example shows how the fields in a very short form letter can be populated:

// A short form-letter for an overdue account
$letter = "Dear #title #name, You owe us $#amount.";

// Set-up an array of three search strings that  
// will be replaced in the form-letter
$fields = array("#title", "#name", "#amount");

// An array of debtors. Each element is an array that
// holds the replacement values for the form-letter
$debtors = array(
    array("Mr", "Cartwright", "146.00"),
    array("Ms", "Yates", "1,662.00"),
    array("Dr", "Smith", "84.75"));

foreach($debtors as $debtor)
  echo "<p>" . str_replace($fields, $debtor, $letter);

The output of this script is as follows:

Dear Mr Cartwright, You owe us $146.00.
Dear Ms Yates, You owe us $1,662.00.
Dear Dr Smith, You owe us $84.75.

If the array of replacement strings is shorter than the array of search strings, the unmatched search strings are replaced with empty strings.

Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.