More Books
PHP 5 Unleashed
PHP 5 Unleashed
Table of Contents
Copyright
Lead Author
Contributing Authors
Acknowledgments
We Want to Hear from You!
Reader Services
Introduction
Organization of the Book
Part I. Working with PHP for General Web Development
Chapter 1. Basic PHP Development
How PHP Scripts Work
Basic PHP Syntax
Basic PHP Data Types
Variable Manipulation
Control Structures
User-Defined Functions
Dynamic Variables and Functions
Multiple File PHP Scripts
References
Strings in PHP
Comparing Strings
Advanced String Comparison
Search and Replacement
Formatting Strings
Strings and Locales
Formatting Date and Time Values
Summary
Chapter 2. Arrays
Basic Arrays
Implementing Arrays
More Array Materials
Chapter 3. Regular Expressions
The Basics of Regular Expressions
Limitations of the Basic Syntax
POSIX Regular Expressions
Perl-Compatible Regular Expressions (PCRE)
PCRE Modifiers
A Few Final Words
Chapter 4. Working with Forms in PHP
HTML Forms 101
Working with Form Submissions in PHP
Summary
Chapter 5. Advanced Form Techniques
Data Manipulation and Conversion
Form Data Integrity
Form Processing
Summary
Chapter 6. Persistent Data Using Sessions and Cookies
HTTP Cookies
PHP Sessions
Advanced Sessions
Summary
Chapter 7. Using Templates
The What and Why of Templates
The Smarty Template Engine
Summary
Part II. Advanced Web Development
Chapter 8. PEAR
What Is PEAR?
Getting and Installing PEAR
Using the PEAR Package Manager
Using the PEAR Website
Using PEAR Packages in Applications
Summary
Reference
Chapter 9. XSLT and Other XML Concerns
Relating XML to HTML
Using XSLT to Describe HTML Output Using XML Input
PHP4 and XSLT Using the DOM XML Module
PHP4 and XSLT Using the XSLT Module
PHP5 and XSLT
Accessing XML Data Using SimpleXML
Generating XML Documents Using PHP
Summary
References
Chapter 10. Debugging and Optimizations
Debugging Your PHP Scripts
Optimizing Your PHP Scripts
Summary
Chapter 11. User Authentication
Authenticating Users in PHP
Securing PHP Code
Summary
Chapter 12. Data Encryption
Shared Secret Versus Public Key
Shared Secret Algorithms
Public Key Cryptography
Using Public Keys in PHP
Summary
Chapter 13. Object-Oriented Programming in PHP
Why Objects?
Creating Basic Classes
Advanced Classes
Special Methods
Class Autoloading
Object Serialization
Exceptions
Iterators
Summary
Chapter 14. Error Handling
The PHP Error-Handling Model
What to Do About Errors
The Default Error Handler
Error Suppression
Custom Error Handlers
Causing Errors
Putting It All Together
Summary
Chapter 15. Working with HTML/XHTML Using Tidy
Introduction
Basic Tidy Usage
Tidy Configuration Options
Using the Tidy Parser
Applications of Tidy
Summary
Chapter 16. Writing Email in PHP
The MIME Protocol
Implementing MIME Email in PHP
Summary
Part III. Building Applications in PHP
Chapter 17. Using PHP for Console Scripting
Core CLI Differences
Working with PHP CLI
CLI Tools and Extensions
Summary
Chapter 18. SOAP and PHP
What Are Web Services?
Installation
Creating Web Services
Consuming Web Services
Looking for Web Services
Summary
Chapter 19. Building WAP-Enabled Websites
What Is WAP?
System Requirements
Introduction to WML
Serving WAP Content
Sample Applications
Summary
Part IV. I/O, System Calls, and PHP
Chapter 20. Working with the File System
Working with Files in PHP
File Permissions
File Access Support Functions
Summary
Chapter 21. Network I/O
DNS/Reverse DNS Lookups
Socket Programming
Network Helper Functions
Summary
Chapter 22. Accessing the Underlying OS from PHP
Introduction
Unix-Specific OS Functionality
Platform-Independent System Functions
A Brief Note About Security
Summary
Part V. Working with Data in PHP
Chapter 23. Introduction to Databases
Using the MySQL Client
Basic MySQL Usage
Summary
Chapter 24. Using MySQL with PHP
Performing Queries from PHP
A MySQLi Session Handler
What Is a Custom Session Handler?
Summary
Chapter 25. Using SQLite with PHP
What Makes SQLite Unique?
Basic SQLite Functionality
Working with PHP UDFs in SQLite
Odds and Ends
Summary
Chapter 26. PHP's dba Functions
Preparations and Settings
Creating a File-Based Database
Writing Data
Reading Data
Sample Application
Conclusion
Part VI. Graphical Output with PHP
Chapter 27. Working with Images
Basic Image Creation Using GD
Using the PHP/GD Drawing Functions
Working with Colors and Brushes
Using Fonts and Printing Strings
General Image Manipulation
Other Graphics Functions
Summary
Chapter 28. Printable Document Generation
A Note Regarding the Examples in This Chapter
Generating Dynamic RTF Documents
Generating Dynamic PDF Documents
Related Resources
Part VII. Appendixes
Appendix A. Installing PHP5 and MySQL
Installing PHP5
Installing MySQL and PHP Modules
Installing PEAR
Appendix B. HTTP Reference
What Is HTTP?
PHP Programming Libraries for HTTP Work
Understanding an HTTP Transaction
HTTP Client Methods
What Comes Back: Server Response Codes
HTTP Headers
Encoding
Identifying Clients and Servers
The "Referer"
Fetching Content from an HTTP Source
Media Types
Cookies: Preserving State and a Tasty Treat
Security and Authorization
Client-Side Caching of HTTP Content
Appendix C. Migrating Applications from PHP4 to PHP5
Configuration
Object-Oriented Programming (OOP)
New Behavior of Functions
Further Reading
Appendix D. Good Programming Techniques and Performance Issues
Common Style Mistakes
Common Security Concerns
Style and SecurityLogging
Summary
Appendix E. Resources and Mailing Lists
Relevant Websites
Mailing Lists and Newsgroups
Index
SYMBOL
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z

Search and Replacement

Using strings without being able to tell what's inside them is a bit like driving around at night with your headlights offyou know the road might be there, but you can't really tell.

PHP offers a wide array of functions for searching and replacing text inside strings using both the traditional "match and replace" approach and a special system known as regular expressions, which we will examine later in this book.

The simplest form of search consists of looking for a substring inside a string. This task is usually performed through a call to strpos($haystack, $needle[, $start]), which returns false if $needle cannot be found inside $haystack, or returns the position of $needle's first character inside $haystack otherwise. If the integer parameter $start is specified, the search operation is performed starting from the character in $haystack whose position corresponds to the value of $start.

For example, the following script will return String found at position 22:

<?php

    $haystack = 'Three merry men and a bottle of wine';

     $pos = strpos ($haystack, 'bottle');

    if ($pos === false)
      echo "String not found\n";
    else
      echo "String found at position $pos\n";

?>

There is one very important detail to notice in the previous script. To determine whether the call to strpos() did indeed succeed and a match for the substring bottle was found inside $haystack, the value of $pos is compared to false using the type-checking operator ===. The reason for this is that the Boolean value false is equivalent to the integer value zero. However, strpos() will return zero if $needle is found starting from the first character of $haystack. Therefore, simply checking the return value of a call to strpos() using an expression like

if (!strpos ($haystack, $needle))
    die ("Failure");

may result in unexpected problems. For example, the following script will incorrectly report that the string "THRee" cannot be found inside the string "THRee merry men":

<?php

    $haystack = 'Three merry men';

    $pos = strpos ($haystack, 'Three');

    if (!$pos)
      echo "String not found\n";
    else
      echo "String found at position $pos\n";

?>

Although strpos() performs its search left-to-right, it is possible to start searching from the end of a string and move backward using the strrpos function. Unlike strpos(), however, strrpos() is able to search for only one character. If you specify a string with more than one character as the $needle parameter, only the first character will be considered.

As you can imagine, strpos() is case sensitive, so that, for example, it wouldn't have been able to find the word "three" in the preceding example.

Interestingly, there is no non-case-sensitive alternative to strpos(). However, PHP provides the strstr function, which offers a functionality that is similar to strpos() and provides a non-case-sensitive variant called stristr().

Unlike strpos(), strstr() actually returns the portion of $haystack that succeeds $needle. The following script, for example, will return String found: merry men:

<?php

    $haystack = 'Three merry men';

    $pos = strstr ($haystack, 'merry');

    if (!$pos)
      echo "String not found\n";
    else
      echo "String found: $pos\n";

?>

Replacing Strings

PHP provides two main functions for performing simple search-and-replace operations. The first one is substr_replace, which can be used whenever you know the location of the substring that must be replaced and its length. For example:

<?php

    $haystack = 'Three merry men';
    $newstr = substr_replace ($haystack, 'sad', 6, 5); 
    echo "$newstr\n";

?>

The preceding script will return Three sad men. The substr_replace function works essentially by cutting out the substring of $haystack delimited by the third (start) and optional fourth (length) parameters, and then replaces it with the string passed to it in the second parameter.

Naturally, you do not always have the luxury of knowing exactly where the substrings to be replaced are in your haystack string; indeed, there might be more than one string that needs to be replaced. In these cases, you can use the str_replace function, which combines the search capabilities of strstr() with the replace functionality of substr_replace.

The syntax of str_replace() is as follows:

str_replace ($search, $replace, $subject)

The function works by finding all the occurrences of $search inside $subject and replacing them with $replace.

Here's an example, which returns THRee sad men:

<?php

    $haystack = 'Three merry men';

    $newstr = str_replace ('merry', 'sad', $haystack); 

    echo "$newstr\n";

?>