Chapter 5- Server Scripting PHP Part II
Chapter 5- Server Scripting PHP Part II
CY430
1
String Processing with Regular Expressions
2
String Processing with Regular Expressions
$search = "Now is the time";
$text = "The quick brown fox jumps over the lazy dog";
if (preg_match($pattern, $text)) {
echo "Match found”
} else {
echo "No match found";
}
?>
4
Character Classes
• Square brackets surrounding a pattern of
characters are called a character class e.g.
[abc].
• A character class always matches a single
character out of a list of specified characters
5
Example
<?php
$text = "He was eating cake in the cafe.";
$pattern = "/ca[kf]e/";
if(preg_match($pattern, $text)){
echo "Match found!";
} else{
echo "Match not found.";}
?>
6
Character Classes
RegExp What it Does
[abc] Matches any one of the characters a, b, or c.
7
Example
$strings = array('apple', 'Banana', 'cherry', '12345', '$
%^&*', 'APPLE’);
$pattern = '/[a-zA-Z]/';
2 [[:digit:]]
It matches any string containing numerical digits 0 through 9.
3 [[:alnum:]]
It matches any string containing alphanumeric characters aA through zZ and 0
through 9.
4 [[:space:]]
It matches any string containing a space.
9
Repetition Quantifiers
• In the previous section we've learned how to
match a single character in a variety of
fashions. But what if you want to match on
more than one character?
10
Repetition Quantifiers
RegExp What it Does
11
Pattern Modifiers
• A pattern modifier allows used to control the
way a pattern match is handled. Pattern
modifiers are placed directly after the regular
expression,
12
String Processing with Regular Expressions
• Function preg_match takes two arguments, a regular-expression
pattern to search for and the string to search.
• The optional third argument to function preg_match is an array
that stores matches to the regular expression.
• The regular expression must be enclosed in delimiters typically a
forward slash (/) is placed at the beginning and end of the regular-
expression pattern.
if(preg_match("/\b([a-zA-Z]*ow)\b/i",
$search))
print( "<p> was found.</p>" );
else print("not found");
?>
14
Example
$search = "My Application";
if(preg_match( "/[m]/i", $search,
$match ) ){
print( " was found." );
print($match[0]);} //it will print "M"
else
print( " not found." );
15
Word Boundaries
• A word boundary character ( \b) helps you search for
the words that begins and/or ends with a pattern.
• For example, the regexp /\bcar/ matches the words
beginning with the pattern car, and would match
cart, carrot, or cartoon, but would not match oscar.
16
String Processing with Regular Expressions
17
Examples
• He?llo would match: Hllo and Hello
19