Regular expressions are patterns for matching, searching, and manipulating strings. PHP uses PCRE (Perl-Compatible Regular Expressions).
$email = "[email protected]";
if (preg_match("/^[\w.+-]+@[\w-]+\.[a-z]{2,}$/i", $email)) {
echo "Valid email";
}
// Capture groups
preg_match("/(\d{4})-(\d{2})-(\d{2})/", "2024-05-01", $matches);
// $matches[0] = "2024-05-01"
// $matches[1] = "2024", [2] = "05", [3] = "01"
$html = "<a>Link 1</a> <a>Link 2</a>";
preg_match_all("!<a>(.+?)</a>!", $html, $matches);
print_r($matches[1]); // ["Link 1", "Link 2"]
$text = "Phone: 123-456-7890";
$clean = preg_replace("/\d/", "*", $text);
// "Phone: ***-***-****"
$parts = preg_split("/[\s,]+/", "one, two, three four");
// ["one", "two", "three", "four"]
/^\d{4}-\d{2}-\d{2}$/ // Date YYYY-MM-DD
/^[a-zA-Z0-9_]{3,20}$/ // Username
/^(?=.*[A-Z])(?=.*\d).{8,}$/ // Strong password
/^https?:\/\/.+/ // URL