Introduction
Regex helps find patterns in text easily. It lets PHP check, search, and change text quickly without writing long code.
Regex helps find patterns in text easily. It lets PHP check, search, and change text quickly without writing long code.
$pattern = '/your-regex-pattern/'; if (preg_match($pattern, $text)) { // pattern found }
/pattern/.preg_match check if pattern exists in text.$pattern = '/hello/'; $text = 'hello world'; if (preg_match($pattern, $text)) { echo 'Found hello'; }
$pattern = '/\d+/'; $text = 'There are 123 apples'; if (preg_match($pattern, $text)) { echo 'Found numbers'; }
This program uses regex to check if an email looks valid. It prints 'Valid email' if the pattern matches.
<?php $pattern = '/^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/i'; $email = 'user@example.com'; if (preg_match($pattern, $email)) { echo 'Valid email'; } else { echo 'Invalid email'; } ?>
Regex can look tricky at first, but it saves a lot of time when working with text.
Always test your regex patterns to make sure they do what you want.
Regex helps PHP find and work with text patterns easily.
It is useful for validation, searching, and replacing text.
Using regex makes your code shorter and faster for text tasks.
$text = 'apple123';
if (preg_match('/\d+/', $text)) {
echo 'Number found';
} else {
echo 'No number';
}
$email = 'user@example.com';
if (preg_match('^[\w.-]+@[\w.-]+\.[a-z]{2,4}$', $email)) {
echo 'Valid email';
} else {
echo 'Invalid email';
}
Pass the test and this pattern moves unknown