Chapter 4. Strings
Most data you encounter as you program will be sequences of characters, or strings. Strings hold people’s names, passwords, addresses, credit-card numbers, photographs, purchase histories, and more. For that reason, PHP has an extensive selection of functions for working with strings.
This chapter shows the many ways to write strings in your programs, including the sometimes-tricky subject of interpolation (placing a variable’s value into a string), then covers the many functions for changing, quoting, and searching strings. By the end of this chapter, you’ll be a string-handling expert.
Quoting String Constants
There are three ways to write a literal string in your program: using single quotes, double quotes, and the here document (heredoc) format derived from the Unix shell. These methods differ in whether they recognize special escape sequences that let you encode other characters or interpolate variables.
The general rule is to use the least powerful quoting mechanism necessary. In practice, this means that you should use single-quoted strings unless you need to include escape sequences or interpolate variables, in which case you should use double-quoted strings. If you want a string that spans many lines, use a heredoc.
Variable Interpolation
When you define a string literal using double quotes or a heredoc, the string is subject to variable interpolation. Interpolation is the process of replacing variable names in the string with the values of those ...