Strings and regular expressions are among the basic tools that help programmers get their jobs done. This five-part article series covers how these are used in PHP. It is excerpted from chapter nine of the book Beginning PHP and Oracle: From Novice to Professional, written by W. Jason Gilmore and Bob Bryla (Apress; ISBN: 1590597702).
Programmers build applications that are based on established rules regarding the classification, parsing, storage, and display of information, whether that information consists of gourmet recipes, store sales receipts, poetry, or some other collection of data. This chapter introduces many of the PHP functions that you’ll undoubtedly use on a regular basis when performing such tasks.
This chapter covers the following topics:
Regular expressions: A brief introduction to regular expressions touches upon the features and syntax of PHP’s two supported regular expression implementations: POSIX and Perl. Following that is a complete introduction to PHP’s respective function libraries.
String manipulation: It’s conceivable that throughout your programming career, you’ll somehow be required to modify every possible aspect of a string. Many of the powerful PHP functions that can help you to do so are introduced in this chapter.
The PEAR Validate_US package: In this and subsequent chapters, various PEAR packages are introduced that are relevant to the respective chapter’s subject matter. This chapter introducesValidate_US, a PEAR package that is useful for validating the syntax for items commonly used in applications of all types, including phone numbers, Social Security numbers (SSNs), ZIP codes, and state abbreviations. (If you’re not familiar with PEAR, it’s introduced in Chapter 11.)
Regular expressions provide the foundation for describing or matching data according to defined syntax rules. A regular expression is nothing more than a pattern of characters itself, matched against a certain parcel of text. This sequence may be a pattern with which you are already familiar, such as the word dog, or it may be a pattern with specific meaning in the context of the world of pattern matching, <(?)>.*<\ /.?>, for example.
PHP is bundled with function libraries supporting both the POSIX and Perl regular expression implementations. Each has its own unique style of syntax and is discussed accordingly in later sections. Keep in mind that innumerable tutorials have been written regarding this matter; you can find information on the Web and in various books. Therefore, this chapter provides just a basic introduction to each, leaving it to you to search out further information.
If you are not already familiar with the mechanics of general expressions, please take some time to read through the short tutorial that makes up the remainder of this section. If you are already a regular expression pro, feel free to skip past the tutorial to the section “PHP’s Regular Expression Functions (POSIX Extended).”