Search code examples
phpregexpcreposix-ere

PHP expressions fail when changing from ereg to preg_match


I have a class that uses PHP's ereg() which is deprecated. Looking on PHP.net I thought I could just get away and change to preg_match()

But I get errors with the regular expressions or they fail!!

Here are two examples:

function input_login() {
    if (ereg("[^-_@\.A-Za-z0-9]", $input_value)) { // WORKS
    // if (preg_match("[^-_@\.A-Za-z0-9]", $input_value)) { // FAILS
        echo "is NOT alphanumeric with characters - _ @ . allowed";
    }
}

// validate email
function validate_email($email) {
    // return eregi("^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$", $email); // FAILS
}

Solution

  • You forgot the delimiters:

    if (preg_match("/[^[email protected]]/", $input_value))
    

    Also, the dot doesn't need to be escaped inside a character class.

    For your validation function, you need to make the regex case-insensitive by using the i modifier:

    return preg_match('/^[_.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i', $email)