PHP CookBook Free Open Book

PHP CookBook

Previous Section Next Section

Recipe 13.9 Escaping Special Characters in a Regular Expression

13.9.1 Problem

You want to have characters such as * or + treated as literals, not as metacharacters, inside a regular expression. This is useful when allowing users to type in search strings you want to use inside a regular expression.

13.9.2 Solution

Use preg_quote( ) to escape Perl-compatible regular-expression metacharacters:

$pattern = preg_quote('The Education of H*Y*M*A*N K*A*P*L*A*N').':(\d+)';
if (preg_match("/$pattern/",$book_rank,$matches)) {
    print "Leo Rosten's book ranked: ".$matches[1];
}

Use quotemeta( ) to escape POSIX metacharacters:

$pattern = quotemeta('M*A*S*H').':[0-9]+';
if (ereg($pattern,$tv_show_rank,$matches)) {
    print 'Radar, Hot Lips, and the gang ranked: '.$matches[1];
}

13.9.3 Discussion

Here are the characters that preg_quote( ) escapes:

. \ + * ? ^ $ [ ] ( ) { } < > = ! | :

Here are the characters that quotemeta( ) escapes:

. \ + * ? ^ $ [ ] ( )

These functions escape the metacharacters with backslash.

The quotemeta( ) function doesn't match all POSIX metacharacters. The characters {, }, and | are also valid metacharacters but aren't converted. This is another good reason to use preg_match( ) instead of ereg( ).

You can also pass preg_quote( ) an additional character to escape as a second argument. It's useful to pass your pattern delimiter (usually /) as this argument so it also gets escaped. This is important if you incorporate user input into a regular-expression pattern. The following code expects $_REQUEST['search_term'] from a web form and searches for words beginning with $_REQUEST['search_term'] in a string $s:

$search_term = preg_quote($_REQUEST['search_term'],'/');
if (preg_match("/\b$search_term/i",$s)) {
   print 'match!';
}

Using preg_quote( ) ensures the regular expression is interpreted properly if, for example, a Magnum, P.I. fan enters t.c. as a search term. Without preg_quote( ), this matches tic, tucker, and any other words whose first letter is t and third letter is c. Passing the pattern delimiter to preg_quote( ) as well makes sure that user input with forward slashes in it, such as CP/M, is also handled correctly.

13.9.4 See Also

Documentation on preg_quote( ) at http://www.php.net/preg-quote and quotemeta( ) at http://www.php.net/quotemeta.

    Previous Section Next Section
    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][Z]


         Main Menu
    Main Page
    Table of content
    Copyright
    Preface
    Chapter 1. Strings
    Chapter 2. Numbers
    Chapter 3. Dates and Times
    Chapter 4. Arrays
    Chapter 5. Variables
    Chapter 6. Functions
    Chapter 7. Classes and Objects
    Chapter 8. Web Basics
    Chapter 9. Forms
    Chapter 10. Database Access
    Chapter 11. Web Automation
    Chapter 12. XML
    Chapter 13. Regular Expressions
    13.1 Introduction
    Recipe 13.2 Switching From ereg to preg
    Recipe 13.3 Matching Words
    Recipe 13.4 Finding the nth Occurrence of a Match
    Recipe 13.5 Choosing Greedy or Nongreedy Matches
    Recipe 13.6 Matching a Valid Email Address
    Recipe 13.7 Finding All Lines in a File That Match a Pattern
    Recipe 13.8 Capturing Text Inside HTML Tags
    Recipe 13.9 Escaping Special Characters in a Regular Expression
    Recipe 13.10 Reading Records with a Pattern Separator
    Chapter 14. Encryption and Security
    Chapter 15. Graphics
    Chapter 16. Internationalization and Localization
    Chapter 17. Internet Services
    Chapter 18. Files
    Chapter 19. Directories
    Chapter 20. Client-Side PHP
    Chapter 21. PEAR
    Colophon
    Index


    More Books
    PHP Hacks
    Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
    The Koran (Holy Qur'an)
    Macromedia Flash 8 Bible
    Search Engine Optimization for Dummies
    YouTube Traffic
    PHP 5 for Dummies
    Harry Potter and The Chamber of Secrets
    Harry Potter and the Sorcerer's Stone
    The Pilgrim's Progress
    Wireless Hacks
    Flash Hacks. 100 Industrial-Strength Tips & Tools
    PayPal Hacks. 100 Industrial-Strength Tips and Tools
    Amazon Hacks
    Pdf Hacks
    The Da Vinci Code
    Google Hacks
    The Holy Bible
    Windows XP For Dummies
    Harry Potter and the Half-Blood Prince
    Seo Book
    Upgrading and Repairing Networks
    Macromedia Dreamweaver 8 UNLEASHED
    Windows XP Annoyances
    Windows XP Hacks
    Microsoft Windows XP Power Toolkit
    Teach Yourself MS Office In 24Hours
    iPod & iTunes Missing Manual
    PC Hacks 100 Industrial-Strength Tips and Tools
    PC Overclocking, Optimization, and Tuning - 2th Edition
    PC Hardware In A Nutshell 3rd Edition
    PC Hardware in a Nutshell, 2nd Edition
    Upgrading and Repairing PCs
    Google for Dummies
    MySQL Cookbook
    Teach Yourself Macromedia Flash 8 In 24 Hours
    PHP CookBook
    Sams Teach Yourself JavaScript in 24 Hours
    PHP5 Manual
    Free Games Paper Airplanes
    500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele