Skip to Main Content
PHP Cookbook
book

PHP Cookbook

by Eric A. Mann
May 2023
Intermediate to advanced content levelIntermediate to advanced
431 pages
8h 55m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

Chapter 4. Strings

Strings are one of the fundamental building blocks of data in PHP. Each string represents an ordered sequence of bytes. Strings can range from human-readable sections of text (like To be or not to be) to sequences of raw bytes encoded as integers (such as \110\145\154\154\157\40\127\157\162\154\144\41).1 Every element of data read or written by a PHP application is represented as a string.

In PHP, strings are typically encoded as ASCII values, although you can convert between ASCII and other formats (like UTF-8) as necessary. Strings can contain null bytes when needed and are essentially limitless in terms of storage so long as the PHP process has adequate memory available.

The most basic way to create a string in PHP is with single quotes. Single-quoted strings are treated as literal statements—there are no special characters or any kind of interpolation of variables. To include a literal single quote within a single-quoted string, you must escape that quote by prefixing it with a backslash—for example, \'. In fact, the only two characters that need to be—or even can be—escaped are the single quote itself or the backslash. Example 4-1 shows single-quoted strings along with their corresponding printed output.

Note

Variable interpolation is the practice of referencing a variable directly by name within a string and letting the interpreter replace the variable with its value at runtime. Interpolation allows for more flexible strings, as you can write a single ...

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.
Start your free trial

You might also like

Clean Code in PHP

Clean Code in PHP

Carsten Windler, Alexandre Daubois
Go Cookbook

Go Cookbook

Sau Sheong Chang

Publisher Resources

ISBN: 9781098121310Errata Page