A Regular Expression (Regex) is a specialized sequence of characters that forms a search pattern. Whether you need to verify that a user's password contains uppercase letters and digits, extract all URLs from an article, or replace bad words in a forum comment, PCRE (Perl Compatible Regular Expressions) in PHP provide unmatched text-pattern matching power.
In PHP, regex patterns are enclosed in forward slashes (delimiters) followed by optional pattern modifiers:
$pattern = "/pattern/modifiers";
/i Modifier: Case-insensitive matching./m Modifier: Multiline matching./s Modifier: Dot matches all characters including newline.preg_match()<?php
$str = "Welcome to Veewom Educational Academy";
$pattern = "/veewom/i"; // Case-insensitive search for "veewom"
if (preg_match($pattern, $str)) {
echo "Match found successfully!<br>";
} else {
echo "Match not found.<br>";
}
?>
Testing if a mobile number starts with 6-9 and contains exactly 10 digits:
<?php
$phone = "9876543210";
// ^ = start, [6-9] = starts with 6,7,8 or 9, [0-9]{9} = 9 more digits, $ = end
$phoneRegex = "/^[6-9][0-9]{9}$/";
if (preg_match($phoneRegex, $phone)) {
echo "Valid 10-digit Indian Mobile Number.<br>";
} else {
echo "Invalid Mobile Number format.<br>";
}
?>
preg_replace()Replacing words or converting plain text URLs into clickable HTML links:
<?php
$text = "Visit https://veewom.com for the best PHP 8 tutorials.";
// Convert raw URLs into clickable anchor tags
$urlRegex = "/(https?:\/\/[^\s]+)/";
$linkedText = preg_replace($urlRegex, '<a href="$1" target="_blank">$1</a>', $text);
echo $linkedText;
?>
High-Frequency Exam Question:
Q: What is the purpose of the preg_split() function?
A: preg_split($pattern, $string) splits a string into an array by a regular expression boundary (e.g. splitting a sentence by any sequence of whitespace or punctuation marks: preg_split('/[\s,]+/', $text)).
Exercise 46.1: Write a regular expression to validate a strong student password: must contain at least 8 characters, at least one uppercase letter, one lowercase letter, and one number.
Exercise 46.2: Use preg_match_all() to extract all email addresses from a large paragraph of text.