How can PHP developers ensure that email addresses entered in a form end with a specific domain?

To ensure that email addresses entered in a form end with a specific domain, PHP developers can use regular expressions to validate the email input and check if it ends with the desired domain. By using a regular expression pattern that matches the domain at the end of the email address, developers can validate the input and prompt users to enter a valid email address if it does not meet the criteria.

$email = $_POST['email'];

$desired_domain = 'example.com';

if (preg_match('/^[a-zA-Z0-9._%+-]+@'.$desired_domain.'$/', $email)) {
    // Email address ends with the desired domain
    echo "Email address is valid.";
} else {
    // Email address does not end with the desired domain
    echo "Please enter a valid email address ending with ".$desired_domain.".";
}