Add Special Characters to Patterns in PHP Scripts - dummies

Add Special Characters to Patterns in PHP Scripts

By Steve Suehring, Janet Valade

Part of PHP, MySQL, JavaScript & HTML5 All-in-One For Dummies Cheat Sheet

When you’re working with PHP scripts, you sometimes need to compare character strings to see if they fit certain characteristics, rather than to see if they match exact values. For example, you might want to identify strings that begin with S or strings that have numbers in them. For this type of comparison, you compare the string to a pattern. These patterns are called regular expressions. Here’s a reference sheet that includes some of the special characters that you’ll use when creating patterns:

Character Meaning Example Match Not a Match
^ Beginning of line ^c cat my cat
$ End of line c$ tic stick
. Any single character .. me, go a
? Preceding item is optional mea?n mean, men moan
( ) Groups literal characters m(ea)n mean men,mn
[ ] Any character in set abc[1-3] abc1,abc2 abc4
[^ ] Any character not in set m[!ea]n min, mon men, man
+ One or more door[1-3]+ door111, door131 door, door55
* Zero or more door[1-3]* door, door311 door4, door445
{ , } Range of repetitions a{2,5} aa,aaaaa a, xx3
Escapes character m*n m*n men, mean
( | | ) Alternate strings (Tom|Tommy) Tom, Tommy Thomas, To