PHP Regular Expression Examples using preg_match()
Posted on January 25, 2016 in PHP, Regular Expressions by Matt Jennings
Example PHP Function Using preg_match()
to Regular Expressions Against Strings
<?php function test($my_pattern, $my_string) { $output = '<p><strong>My String:</strong><br />' . $my_string . '</p>'; $output .= '<p><strong>My Pattern:</strong><br />' . $my_pattern .'</p>'; if(preg_match($my_pattern, $my_string)) { $match = 'MATCH'; } else { $match = 'DOES NOT MATCH'; } $output .= '<p><strong>Pattern Match?</strong><br />' . $match . '</p>'; $output .= '<p><hr /></p>'; echo $output; } ?>
Example PHP test()
Function Call
<?php test('/awesome/', 'This website rocks!'); ?>
Example HTML Output to Match awesome
Anywhere in a String
My String:
This website rocks!
My Pattern:
/awesome/
Pattern Match?
DOES NOT MATCH
Match awesome
, Case Insensitive, Anywhere in a String
My String:
This site is totally AWESOME!
My Pattern:
/awesome/i
Pattern Match?
MATCH
Match awesome
and/or rocks
, Case Insensitive, Anywhere in a String
My String:
This website ROCKS!
My Pattern:
/awesome|rocks/i
Pattern Match?
MATCH
Match Digits 0
through 9
at the Start of a String
My String:
1 December
My Pattern:
/^[0-9]/
Pattern Match?
MATCH
My String:
1 December
My Pattern:
/^\d/
Pattern Match?
MATCH
Match jpg
, Case Insensitive, at the End of a String
My String:
scotland.JPG
My Pattern:
/jpg$/i
Pattern Match?
MATCH
Match a String with woman
in It and No Other Characters
My String:
woman
My Pattern:
/^woman$/
Pattern Match?
DOES NOT MATCH
Match a String with a Canadian Zip Code Which has [Letter][Number][Letter] [Number][Letter][Number]
and All Capital Letters
My String:
M5K 1A1
My Pattern:
/[A-Z]\d[A-Z] \d[A-Z]\d/
Pattern Match?
MATCH
My String:
M5K 1A1
My Pattern:
/[A-Z][0-9][A-Z] [0-9][A-Z][0-9]/
Pattern Match?
MATCH
Match a String that has 6 to 8 Characters, Inclusive
My String:
username
My Pattern:
/^\w{6,8}/
Pattern Match?
MATCH
Match a String has 5 Numbers, and Optional a -
with 4 More Numbers for an American Zip Code
My String:
14609-1234
My Pattern:
/^\d{5}(-\d{4})?$/
Pattern Match?
MATCH
Match a String that Uses Non-Latin Characters that are Supported by UTF-8
My String:
ดั๊กลาส
My Pattern:
/ดั๊กลาส/u
Pattern Match?
MATCH
Match a String with a Canadian Zip Code Which has [Letter][Number][Letter][space][Number][Letter][Number]
and All Capital Letters
My String:
M5K 1A1
My Pattern:
/[A-Z]\d[A-Z]\s\d[A-Z]\d/
Pattern Match?
MATCH