Kastoli
Kastoli

Reputation: 105

PHP Regex preg_match Email Validation

$email = '[email protected]';
if(preg_match(\w+(@business.com)\z), $email){code goes here}

I'm trying to execute code in the "code goes here" section of this condition when $email contains an email address that ends in exactly @business.com.

I feel like I'm perhaps misunderstanding how preg_match works, but I can't find any information as to why the if statement is evaluating as false.

There are many, many examples and other people having similar problems, but the solution to their problems doesn't seem to highlight any issues with my code.

I was working off this example:

http://php.net/manual/en/function.preg-match.php

<?php
// The "i" after the pattern delimiter indicates a case-insensitive search
if (preg_match("/php/i", "PHP is the web scripting language of choice.")) {
    echo "A match was found.";
} else {
    echo "A match was not found.";
}
?>

Upvotes: 1

Views: 1117

Answers (1)

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21422

No need to use regex you can simply use strstr function of PHP like as

if(strstr('[email protected]',"@") == "@business.com"){
  // code goes here
}

or for using regex you can simply use Positive Lookbehind like as

if(preg_match('~(?<=\w)(@business.com)~',$string)!==false){
    // code goes here
}

Demo

Upvotes: 1

Related Questions