05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter CHAPTER 4 4<br />

Strings<br />

Most data you encounter as you program will be sequences of characters, or strings.<br />

Strings hold people’s names, passwords, addresses, credit-card numbers, photographs,<br />

purchase histories, and more. For that reason, <strong>PHP</strong> has an extensive selection<br />

of functions for working with strings.<br />

This chapter shows the many ways to write strings in your programs, including the<br />

sometimes-tricky subject of interpolation (placing a variable’s value into a string),<br />

then covers the many functions for changing, quoting, and searching strings. By the<br />

end of this chapter, you’ll be a string-handling expert.<br />

Quoting String Constants<br />

There are three ways to write a literal string in your program: using single quotes,<br />

double quotes, and the here document (heredoc) format derived from the Unix shell.<br />

These methods differ in whether they recognize special escape sequences that let you<br />

encode other characters or interpolate variables.<br />

The general rule is to use the least powerful quoting mechanism necessary. In practice,<br />

this means that you should use single-quoted strings unless you need to include<br />

escape sequences or interpolate variables, in which case you should use doublequoted<br />

strings. If you want a string that spans many lines, use a heredoc.<br />

Variable Interpolation<br />

When you define a string literal using double quotes or a heredoc, the string is subject<br />

to variable interpolation. Interpolation is the process of replacing variable names<br />

in the string with the values of those variables. There are two ways to interpolate<br />

variables into strings—the simple way and the complex way.<br />

The simple way is to just put the variable name in a double-quoted string or heredoc:<br />

72<br />

$who = 'Kilroy';<br />

$where = 'here';<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!