Imagine you want to find all email addresses in a long text. Why is regex useful in PHP for this task?
Think about how you find a pattern, not just a word.
Regex helps find patterns like emails, phone numbers, or dates inside text, which simple search cannot do.
Look at this PHP code that uses regex to check if a string contains digits:
$text = 'Hello123';
if (preg_match('/\d+/', $text)) {
echo 'Digits found';
} else {
echo 'No digits';
}What will it print?
\d+ means one or more digits.
The string 'Hello123' contains digits '123', so preg_match returns true and prints 'Digits found'.
Consider this PHP code that extracts all words starting with 'a' or 'A':
$text = 'Apple and apricot are awesome';
preg_match_all('/\b[aA]\w*/', $text, $matches);
print_r($matches[0]);What is the output?
\b means word boundary, [aA] matches 'a' or 'A', \w* matches letters after.
The regex finds all words starting with 'a' or 'A': Apple, and, apricot, are, awesome.
Why would a PHP developer choose regex instead of simple string functions like strpos or strstr for pattern matching?
Think about matching patterns like phone numbers or emails.
Regex allows matching flexible patterns with rules, while string functions only find exact substrings.
Look at this PHP code snippet:
$pattern = '/(abc/'; $text = 'abcdef'; preg_match($pattern, $text, $matches); print_r($matches);
What error will this code produce?
Check if the regex pattern is correctly closed.
The regex pattern '/(abc/' is missing a closing parenthesis, causing a compilation error in preg_match.