Chapter 4. Strings
Most data you encounter as you program will be sequences of characters, or strings. Strings can hold people’s names, passwords, addresses, credit card numbers, links to 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 create strings in your programs, including the sometimes tricky subject of interpolation (placing a variable’s value into a string), then covers functions for changing, quoting, manipulating, and searching strings. By the end of this chapter, you’ll be a string-handling expert.
Quoting String Constants
There are four ways to write a string literal in your PHP code: using single quotes, double quotes, the here document (heredoc) format derived from the Unix shell, and its “cousin” now document (nowdoc). These methods differ in whether they recognize special escape sequences that let you encode other characters or interpolate variables.
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 their contained values. There are two ways to interpolate variables into strings.
The simpler of the two ways is to put the variable name in a double-quoted string or in a heredoc:
$who='Kilroy';$where='here';echo"$whowas$where";Kilroywashere
The other way is to surround the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access