PHP supports regular expressions (regex), which are patterns used to match character combinations in strings. Regular expressions are powerful tools for searching and manipulating text, validating inputs, and performing complex search and replace operations.
PHP regex functions use Perl Compatible Regular Expressions (PCRE). Patterns are enclosed within delimiters like /pattern/ and can include modifiers such as i for case-insensitive matching.
// Search for a price pattern using preg_match()
<?php
$text = "The price of the item is $20.";
$pattern = "/\$\d+/";
if (preg_match($pattern, $text, $matches)) {
echo "Found price: " . $matches[0] . "<br>";
} else {
echo "No price found.<br>";
}
?>
Found price: $20
The regex /\$\d+/ matches a dollar sign followed by one or more digits.
Try modifying the pattern to detect emails or phone numbers. Regular expressions allow flexible pattern matching without complex logic.