Regular expressions are used to match patterns in strings for validation, search, and replace operations.
Checks if a pattern matches a string (returns 1 if match, 0 if not):
$email = "test@example.com";
if (preg_match("/^[\w.-]+@[\w.-]+\.\w+$/", $email)) {
echo "Valid email";
}Replaces matched patterns in a string:
$text = "I like cats.";
$newText = preg_replace("/cats/", "dogs", $text);
echo $newText; // I like dogs.i – Case-insensitivem – Multiline modeu – Unicode supports – Dot matches newlinespreg_match("/php/i", "PHP is great"); // Match\\d – digit\\w – word character. – any character^ – start of string$ – end of string*, +, ? – quantifierspreg_match("/^\d{3}-\d{2}-\d{4}$/", "123-45-6789");if (preg_match("/^[a-zA-Z ]+$/", $_POST['name'])) {
echo "Valid name";
} else {
echo "Invalid name";
}preg_last_error() returns error codes after a regex operation fails:
if (preg_last_error() !== PREG_NO_ERROR) {
echo "Regex error occurred.";
}Ask the AI if you need help understanding or want to dive deeper in any topic