You are previewing Programming PHP, 3rd Edition.

Programming PHP, 3rd Edition

Cover of Programming PHP, 3rd Edition by Kevin Tatroe... Published by O'Reilly Media, Inc.
  1. Dedication
  2. Special Upgrade Offer
  3. Foreword
  4. Preface
    1. Audience
    2. Assumptions This Book Makes
    3. Contents of This Book
    4. Conventions Used in This Book
    5. Using Code Examples
    6. Safari® Books Online
    7. How to Contact Us
    8. Acknowledgments
      1. Kevin Tatroe
      2. Peter MacIntyre
  5. 1. Introduction to PHP
    1. What Does PHP Do?
    2. A Brief History of PHP
      1. The Evolution of PHP
      2. The Widespread Use of PHP
    3. Installing PHP
    4. A Walk Through PHP
      1. Configuration Page
      2. Forms
      3. Databases
      4. Graphics
  6. 2. Language Basics
    1. Lexical Structure
      1. Case Sensitivity
      2. Statements and Semicolons
      3. Whitespace and Line Breaks
      5. Literals
      6. Identifiers
      7. Keywords
    2. Data Types
      1. Integers
      2. Floating-Point Numbers
      3. Strings
      4. Booleans
      5. Arrays
      6. Objects
      7. Resources
      8. Callbacks
      9. NULL
    3. Variables
      1. Variable Variables
      2. Variable References
      3. Variable Scope
      4. Garbage Collection
    4. Expressions and Operators
      1. Number of Operands
      2. Operator Precedence
      3. Operator Associativity
      4. Implicit Casting
      5. Arithmetic Operators
      6. String Concatenation Operator
      7. Auto-increment and Auto-decrement Operators
      8. Comparison Operators
      9. Bitwise Operators
      10. Logical Operators
      11. Casting Operators
      12. Assignment Operators
      13. Miscellaneous Operators
    5. Flow-Control Statements
      1. if
      2. switch
      3. while
      4. for
      5. foreach
      6. try...catch
      7. declare
      8. exit and return
      9. goto
    6. Including Code
    7. Embedding PHP in Web Pages
      1. Standard (XML) Style
      2. SGML Style
      3. ASP Style
      4. Script Style
      5. Echoing Content Directly
  7. 3. Functions
    1. Calling a Function
    2. Defining a Function
    3. Variable Scope
      1. Global Variables
      2. Static Variables
    4. Function Parameters
      1. Passing Parameters by Value
      2. Passing Parameters by Reference
      3. Default Parameters
      4. Variable Parameters
      5. Missing Parameters
      6. Type Hinting
    5. Return Values
    6. Variable Functions
    7. Anonymous Functions
  8. 4. Strings
    1. Quoting String Constants
      1. Variable Interpolation
      2. Single-Quoted Strings
      3. Double-Quoted Strings
      4. Here Documents
    2. Printing Strings
      1. echo
      2. print()
      3. printf()
      4. print_r() and var_dump()
    3. Accessing Individual Characters
    4. Cleaning Strings
      1. Removing Whitespace
      2. Changing Case
    5. Encoding and Escaping
      1. HTML
      2. URLs
      3. SQL
      4. C-String Encoding
    6. Comparing Strings
      1. Exact Comparisons
      2. Approximate Equality
    7. Manipulating and Searching Strings
      1. Substrings
      2. Miscellaneous String Functions
      3. Decomposing a String
      4. String-Searching Functions
    8. Regular Expressions
      1. The Basics
      2. Character Classes
      3. Alternatives
      4. Repeating Sequences
      5. Subpatterns
      6. Delimiters
      7. Match Behavior
      8. Character Classes
      9. Anchors
      10. Quantifiers and Greed
      11. Noncapturing Groups
      12. Backreferences
      13. Trailing Options
      14. Inline Options
      15. Lookahead and Lookbehind
      16. Cut
      17. Conditional Expressions
      18. Functions
      19. Differences from Perl Regular Expressions
  9. 5. Arrays
    1. Indexed Versus Associative Arrays
    2. Identifying Elements of an Array
    3. Storing Data in Arrays
      1. Adding Values to the End of an Array
      2. Assigning a Range of Values
      3. Getting the Size of an Array
      4. Padding an Array
    4. Multidimensional Arrays
    5. Extracting Multiple Values
      1. Slicing an Array
      2. Splitting an Array into Chunks
      3. Keys and Values
      4. Checking Whether an Element Exists
      5. Removing and Inserting Elements in an Array
    6. Converting Between Arrays and Variables
      1. Creating Variables from an Array
      2. Creating an Array from Variables
    7. Traversing Arrays
      1. The foreach Construct
      2. The Iterator Functions
      3. Using a for Loop
      4. Calling a Function for Each Array Element
      5. Reducing an Array
      6. Searching for Values
    8. Sorting
      1. Sorting One Array at a Time
      2. Natural-Order Sorting
      3. Sorting Multiple Arrays at Once
      4. Reversing Arrays
      5. Randomizing Order
    9. Acting on Entire Arrays
      1. Calculating the Sum of an Array
      2. Merging Two Arrays
      3. Calculating the Difference Between Two Arrays
      4. Filtering Elements from an Array
    10. Using Arrays
      1. Sets
      2. Stacks
    11. Iterator Interface
  10. 6. Objects
    1. Terminology
    2. Creating an Object
    3. Accessing Properties and Methods
    4. Declaring a Class
      1. Declaring Methods
      2. Declaring Properties
      3. Declaring Constants
      4. Inheritance
      5. Interfaces
      6. Traits
      7. Abstract Methods
      8. Constructors
      9. Destructors
    5. Introspection
      1. Examining Classes
      2. Examining an Object
      3. Sample Introspection Program
    6. Serialization
  11. 7. Web Techniques
    1. HTTP Basics
    2. Variables
    3. Server Information
    4. Processing Forms
      1. Methods
      2. Parameters
      3. Self-Processing Pages
      4. Sticky Forms
      5. Multivalued Parameters
      6. Sticky Multivalued Parameters
      7. File Uploads
      8. Form Validation
    5. Setting Response Headers
      1. Different Content Types
      2. Redirections
      3. Expiration
      4. Authentication
    6. Maintaining State
      1. Cookies
      2. Sessions
      3. Combining Cookies and Sessions
    7. SSL
  12. 8. Databases
    1. Using PHP to Access a Database
    2. Relational Databases and SQL
      1. PHP Data Objects
    3. MySQLi Object Interface
      1. Retrieving Data for Display
    4. SQLite
    5. Direct File-Level Manipulation
    6. MongoDB
      1. Retrieving Data
      2. Inserting More Complex Data
  13. 9. Graphics
    1. Embedding an Image in a Page
    2. Basic Graphics Concepts
    3. Creating and Drawing Images
      1. The Structure of a Graphics Program
      2. Changing the Output Format
      3. Testing for Supported Image Formats
      4. Reading an Existing File
      5. Basic Drawing Functions
    4. Images with Text
      1. Fonts
      2. TrueType Fonts
    5. Dynamically Generated Buttons
      1. Caching the Dynamically Generated Buttons
      2. A Faster Cache
    6. Scaling Images
    7. Color Handling
      1. Using the Alpha Channel
      2. Identifying Colors
      3. True Color Indexes
      4. Text Representation of an Image
  14. 10. PDF
    1. PDF Extensions
    2. Documents and Pages
      1. A Simple Example
      2. Initializing the Document
      3. Outputting Basic Text Cells
    3. Text
      1. Coordinates
      2. Text Attributes
      3. Page Headers, Footers, and Class Extension
      4. Images and Links
      5. Tables and Data
  15. 11. XML
    1. Lightning Guide to XML
    2. Generating XML
    3. Parsing XML
      1. Element Handlers
      2. Character Data Handler
      3. Processing Instructions
      4. Entity Handlers
      5. Default Handler
      6. Options
      7. Using the Parser
      8. Errors
      9. Methods as Handlers
      10. Sample Parsing Application
    4. Parsing XML with DOM
    5. Parsing XML with SimpleXML
    6. Transforming XML with XSLT
  16. 12. Security
    1. Filter Input
    2. Cross-Site Scripting
      1. SQL Injection
    3. Escape Output
      1. Filenames
    4. Session Fixation
    5. File Uploads
      1. Distrust Browser-Supplied Filenames
      2. Beware of Filling Your Filesystem
      3. Surviving register_globals
    6. File Access
      1. Restrict Filesystem Access to a Specific Directory
      2. Get It Right the First Time
      3. Don’t Use Files
      4. Session Files
      5. Concealing PHP Libraries
    7. PHP Code
    8. Shell Commands
    9. More Information
    10. Security Recap
  17. 13. Application Techniques
    1. Code Libraries
    2. Templating Systems
    3. Handling Output
      1. Output Buffering
      2. Compressing Output
    4. Error Handling
      1. Error Reporting
      2. Error Suppression
      3. Triggering Errors
      4. Defining Error Handlers
    5. Performance Tuning
      1. Benchmarking
      2. Profiling
      3. Optimizing Execution Time
      4. Optimizing Memory Requirements
      5. Reverse Proxies and Replication
  18. 14. PHP on Disparate Platforms
    1. Writing Portable Code for Windows and Unix
      1. Determining the Platform
      2. Handling Paths Across Platforms
      3. The Server Environment
      4. Sending Mail
      5. End-of-Line Handling
      6. End-of-File Handling
      7. External Commands
      8. Common Platform-Specific Extensions
    2. Interfacing with COM
      1. Background
      2. PHP Functions
      3. Determining the API
  19. 15. Web Services
    1. REST Clients
      1. Responses
      2. Retrieving Resources
      3. Updating Resources
      4. Creating Resources
      5. Deleting Resources
    2. XML-RPC
      1. Servers
      2. Clients
  20. 16. Debugging PHP
    1. The Development Environment
    2. The Staging Environment
    3. The Production Environment
    4. php.ini Settings
    5. Manual Debugging
    6. Error Log
    7. IDE Debugging
    8. Additional Debugging Techniques
  21. 17. Dates and Times
  22. A. Function Reference
    1. PHP Functions by Category
      1. Arrays
      2. Classes and Objects
      3. Date and Time
      4. Directories
      5. Errors and Logging
      6. Program Execution
      7. Filesystem
      8. Data Filtering
      9. Functions
      10. PHP Options/Info
      11. Mail
      12. Math
      13. Miscellaneous Functions
      14. Network
      15. Output Buffering
      16. Session Handling
      17. Streams
      18. Strings
      19. PHP Language Tokenizer
      20. URLs
      21. Variables
    2. Alphabetical Listing of PHP Functions
  23. Index
  24. About the Authors
  25. Colophon
  26. Special Upgrade Offer
  27. Copyright
O'Reilly logo

Manipulating and Searching Strings

PHP has many functions to work with strings. The most commonly used functions for searching and modifying strings are those that use regular expressions to describe the string in question. The functions described in this section do not use regular expressions—they are faster than regular expressions, but they work only when you’re looking for a fixed string (for instance, if you’re looking for "12/11/01" rather than “any numbers separated by slashes”).


If you know where the data that you are interested in lies in a larger string, you can copy it out with the substr() function:

$piece = substr(string, start [, length ]);

The start argument is the position in string at which to begin copying, with 0 meaning the start of the string. The length argument is the number of characters to copy (the default is to copy until the end of the string). For example:

$name  = "Fred Flintstone";
$fluff = substr($name, 6, 4);  // $fluff is "lint"
$sound = substr($name, 11);    // $sound is "tone"

To learn how many times a smaller string occurs in a larger one, use substr_count():

$number = substr_count(big_string, small_string);

For example:

$sketch = <<< EndOfSketch
Well, there's egg and bacon; egg sausage and bacon; egg and spam;
egg bacon and spam; egg bacon sausage and spam; spam bacon sausage
and spam; spam egg spam spam bacon and spam; spam sausage spam spam
bacon spam tomato and spam;
$count = substr_count($sketch, "spam");
print("The word spam occurs {$count} times.");
The word spam occurs 14 times.

The substr_replace() function permits many kinds of string modifications:

$string = substr_replace(original, new, start [, length ]);

The function replaces the part of original indicated by the start (0 means the start of the string) and length values with the string new. If no fourth argument is given, substr_replace() removes the text from start to the end of the string.

For instance:

$greeting = "good morning citizen";
$farewell = substr_replace($greeting, "bye", 5, 7);
// $farewell is "good bye citizen"

Use a length of 0 to insert without deleting:

$farewell = substr_replace($farewell, "kind ", 9, 0);
// $farewell is "good bye kind citizen"

Use a replacement of "" to delete without inserting:

$farewell = substr_replace($farewell, "", 8);
// $farewell is "good bye"

Here’s how you can insert at the beginning of the string:

$farewell = substr_replace($farewell, "now it's time to say ", 0, 0);
// $farewell is "now it's time to say good bye"'

A negative value for start indicates the number of characters from the end of the string from which to start the replacement:

$farewell = substr_replace($farewell, "riddance", 3);
// $farewell is "now it's time to say good riddance"

A negative length indicates the number of characters from the end of the string at which to stop deleting:

$farewell = substr_replace($farewell, "", 8, 5);
// $farewell is "now it's time to say good dance"

Miscellaneous String Functions

The strrev() function takes a string and returns a reversed copy of it:

$string = strrev(string);

For example:

echo strrev("There is no cabal");
labac on si erehT

The str_repeat() function takes a string and a count and returns a new string consisting of the argument string repeated count times:

$repeated = str_repeat(string, count);

For example, to build a crude wavy horizontal rule:

echo str_repeat('_.-.', 40);

The str_pad() function pads one string with another. Optionally, you can say what string to pad with, and whether to pad on the left, right, or both:

$padded = str_pad(to_pad, length [, with [, pad_type ]]);

The default is to pad on the right with spaces:

$string = str_pad('Fred Flintstone', 30);
echo "{$string}:35:Wilma";
Fred Flintstone   :35:Wilma

The optional third argument is the string to pad with:

$string = str_pad('Fred Flintstone', 30, '. ');
echo "{$string}35";
Fred Flintstone. . . . . . . .35

The optional fourth argument can be STR_PAD_RIGHT (the default), STR_PAD_LEFT, or STR_PAD_BOTH (to center). For example:

echo '[' . str_pad('Fred Flintstone', 30, ' ', STR_PAD_LEFT) . "]\n";
echo '[' . str_pad('Fred Flintstone', 30, ' ', STR_PAD_BOTH) . "]\n";
[               Fred Flintstone]
[       Fred Flintstone        ]

Decomposing a String

PHP provides several functions to let you break a string into smaller components. In increasing order of complexity, they are explode(), strtok(), and sscanf().

Exploding and imploding

Data often arrives as strings, which must be broken down into an array of values. For instance, you might want to separate out the comma-separated fields from a string such as "Fred,25,Wilma." In these situations, use the explode() function:

$array = explode(separator, string [, limit]);

The first argument, separator, is a string containing the field separator. The second argument, string, is the string to split. The optional third argument, limit, is the maximum number of values to return in the array. If the limit is reached, the last element of the array contains the remainder of the string:

$input  = 'Fred,25,Wilma';
$fields = explode(',', $input);
// $fields is array('Fred', '25', 'Wilma')
$fields = explode(',', $input, 2);
// $fields is array('Fred', '25,Wilma')

The implode() function does the exact opposite of explode()—it creates a large string from an array of smaller strings:

$string = implode(separator, array);

The first argument, separator, is the string to put between the elements of the second argument, array. To reconstruct the simple comma-separated value string, simply say:

$fields = array('Fred', '25', 'Wilma');
$string = implode(',', $fields);   // $string is 'Fred,25,Wilma'

The join() function is an alias for implode().


The strtok() function lets you iterate through a string, getting a new chunk (token) each time. The first time you call it, you need to pass two arguments: the string to iterate over and the token separator. For example:

$firstChunk = strtok(string, separator);

To retrieve the rest of the tokens, repeatedly call strtok() with only the separator:

$nextChunk  = strtok(separator);

For instance, consider this invocation:

$string = "Fred,Flintstone,35,Wilma";
$token  = strtok($string, ",");

while ($token !== false) {
  echo("{$token}<br />");
  $token = strtok(",");

The strtok() function returns false when there are no more tokens to be returned.

Call strtok() with two arguments to reinitialize the iterator. This restarts the tokenizer from the start of the string.


The sscanf() function decomposes a string according to a printf()-like template:

$array = sscanf(string, template);
$count = sscanf(string, template, var1, ... );

If used without the optional variables, sscanf() returns an array of fields:

$string = "Fred\tFlintstone (35)";
$a = sscanf($string, "%s\t%s (%d)");
  [0] => Fred
  [1] => Flintstone
  [2] => 35

Pass references to variables to have the fields stored in those variables. The number of fields assigned is returned:

$string = "Fred\tFlintstone (35)";
$n = sscanf($string, "%s\t%s (%d)", $first, $last, $age);
echo "Matched {$n} fields: {$first} {$last} is {$age} years old";
Matched 3 fields: Fred Flintstone is 35 years old

String-Searching Functions

Several functions find a string or character within a larger string. They come in three families: strpos() and strrpos(), which return a position; strstr(), strchr(), and friends, which return the string they find; and strspn() and strcspn(), which return how much of the start of the string matches a mask.

In all cases, if you specify a number as the “string” to search for, PHP treats that number as the ordinal value of the character to search for. Thus, these function calls are identical because 44 is the ASCII value of the comma:

$pos = strpos($large, ","); // find first comma
$pos = strpos($large, 44);  // also find first comma

All the string-searching functions return false if they can’t find the substring you specified. If the substring occurs at the beginning of the string, the functions return 0. Because false casts to the number 0, always compare the return value with === when testing for failure:

if ($pos === false) {
  // wasn't found
else {
  // was found, $pos is offset into string

Searches returning position

The strpos() function finds the first occurrence of a small string in a larger string:

$position = strpos(large_string, small_string);

If the small string isn’t found, strpos() returns false.

The strrpos() function finds the last occurrence of a character in a string. It takes the same arguments and returns the same type of value as strpos().

For instance:

$record = "Fred,Flintstone,35,Wilma";
$pos = strrpos($record, ",");  // find last comma
echo("The last comma in the record is at position {$pos}");
The last comma in the record is at position 18

Searches returning rest of string

The strstr() function finds the first occurrence of a small string in a larger string and returns from that small string on. For instance:

$record = "Fred,Flintstone,35,Wilma";
$rest = strstr($record, ",");  // $rest is ",Flintstone,35,Wilma"

The variations on strstr() are:


Case-insensitive strstr()


Alias for strstr()


Find last occurrence of a character in a string

As with strrpos(), strrchr() searches backward in the string, but only for a single character, not for an entire string.

Searches using masks

If you thought strrchr() was esoteric, you haven’t seen anything yet. The strspn() and strcspn() functions tell you how many characters at the beginning of a string are composed of certain characters:

$length = strspn(string, charset);

For example, this function tests whether a string holds an octal number:

function isOctal($str)
  return strspn($str, '01234567') == strlen($str);

The c in strcspn() stands for complement—it tells you how much of the start of the string is not composed of the characters in the character set. Use it when the number of interesting characters is greater than the number of uninteresting characters. For example, this function tests whether a string has any NUL-bytes, tabs, or carriage returns:

function hasBadChars($str)
  return strcspn($str, "\n\t\0") != strlen($str);

Decomposing URLs

The parse_url() function returns an array of components of a URL:

$array = parse_url(url);

For example:

$bits = parse_url("");

  [scheme] => http
  [host] =>
  [user] => me
  [pass] => secret
  [path] => /cgi-bin/board
  [query] => user=fred)

The possible keys of the hash are scheme, host, port, user, pass, path, query, and fragment.

The best content for your career. Discover unlimited learning on demand for around $1/day.