How can regular expressions (regex) be used to validate text input in PHP?

Regular expressions (regex) can be used in PHP to validate text input by defining patterns that the input must match. This can be useful for ensuring that user input follows a specific format, such as a valid email address or phone number. By using regex, you can easily check if the input meets your criteria before processing it further in your PHP code.

$input = "example@email.com";

if (preg_match("/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/", $input)) {
    echo "Input is a valid email address.";
} else {
    echo "Input is not a valid email address.";
}