This question already has answers here:
How can I convert ereg expressions to preg in PHP?
(4 answers)
Closed 9 years ago.
Hi ı know that we do not eregi but preg_match but when ı change only eregi code it doesnt work, how can ı change the code below please just a little help, ı am a newbie
function verify_valid_email($emailtocheck)
{
$eregicheck = "^([-!#\$%&'*+./0-9=?A-Z^_`a-z{|}~])+#([-!#\$%&'*+/0-9=?A-Z^_`a-z{|}~]+\\.)+[a-zA-Z]{2,4}\$";
return eregi($eregicheck, $emailtocheck);
}
function verify_email_unique($emailtocheck)
{
global $config,$conn;
$query = "select count(*) as total from members where email='".mysql_real_escape_string($emailtocheck)."' limit 1";
$executequery = $conn->execute($query);
$totalemails = $executequery->fields[total];
if ($totalemails >= 1)
{
return false;
}
else
{
return true;
}
}
If you need to validate e-mail addresses, you can look at this page which provides a working example using only filter_var() :
if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
echo "This ($email_a) email address is considered valid.";
};
So in your code, you should just drop all the regex/eregi stuff and use this instead :
return filter_var($emailtocheck, FILTER_VALIDATE_EMAIL);
If you want to do it this way, you can base yourself on the following methods:
<?php
$email = \"abc123#somewhere\"; // Invalid email address
//$email = \"somebody#somesite.com\"; // Valid email address
// Set up regular expression strings to evaluate the value of email variable against
$regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
// Run the preg_match() function on regex against the email address
if (preg_match($regex, $email)) {
echo $email . \" is a valid email. We can accept it.\";
} else {
echo $email . \" is an invalid email. Please try again.\";
}
?>
or:
$string = "$emailtocheck";
if (preg_match(
'/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\#[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/',
$string)) {
echo "Successful.";
}
or:
<?php
$email = "abc123#sdsd.com";
$regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
if (preg_match($regex, $email)) {
echo $email . " is a valid email. We can accept it.";
} else {
echo $email . " is an invalid email. Please try again.";
}
?>
Source: https://stackoverflow.com/a/13719991/1415724
or:
<?php
// check e-mail address
// display success or failure message
if (!preg_match("/^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*#([a-zA-Z0-9_-
])+(\.[a-zA-Z0-9_-]+)*\.([a-zA-Z]{2,6})$/", $_POST['e-mail'])) {
die("Invalid e-mail address");
}
echo "Valid e-mail address, processing...";
?>
Source: http://www.techrepublic.com/article/regular-expression-engine-simplifies-e-mail-validation-in-php/
Plus, you can try what André Daniel wrote as an answer as well. You have many choices.
Related
This question already has answers here:
How to match all email addresses at a specific domain using regex?
(5 answers)
Closed 4 years ago.
I am new to regular expressions and need some help. I need to use a regular expression to validate an email so it has a specific email so only emails ending in #School.edu work, as of right now i have
$username = $_REQUEST["username"];
$password = $_REQUEST["pass"];
$repeatP = $_REQUEST["repeat"];
//Username is Acceptable, Passwords Match and Appropirate Size
if(preg_match("/^[a-zA-Z0-9]+\oneonta.edu$/i", $username)) {
$userCheck = true;
?> <p>Username is Acceptable</p>
<?
}
else {
?><p>Error: Username is Unacceptable, Please go back and try again</p>
<?
}
I'm using School.edu as an example for my schools edu, I just don't get how to it only allow School.edu emails
one option:
$mystring = '#oneonta.edu';
$pos = strpos($mystring, $_REQUEST["username"]);
if ($pos !== false) {
echo "<p>Username is Acceptable</p>";
} else {
echo "<p>Error: Username is Unacceptable, Please go back and try again</p> ";
}
another
if(substr($_REQUEST["username"], -12)=='#oneonta.edu'){
echo "<p>Username is Acceptable</p>";
}else{
echo "<p>Error: Username is Unacceptable, Please go back and try again</p> ";
}
more ?
$pieces = explode("#", $_REQUEST["username"]);
if($pieces[1]=='oneonta.edu'){
echo "<p>Username is Acceptable</p>";
}else{
echo "<p>Error: Username is Unacceptable, Please go back and try again</p> ";
}
I am trying to build a form with good email validation, I am trying to use filter_var() combined with preg_match(), but with my if statement below it isn't working. Only one of the conditions is being met it seems. How else could I write this so that it works?
$email = (isset($scrubbed['email']))
? filter_var($scrubbed['email'], FILTER_VALIDATE_EMAIL, FILTER_SANITIZE_EMAIL)
: NULL
;
if ((!$email) && (!preg_match("/^[\w.-]+#[\w.-]+\.[A-Za-z]{2,6}$/", $email))) {
echo 'Invalid Email Address, please correct errors';
} else {
$email = strip_tags($scrubbed['email']);
}
What's the purpose of validating the email address again? PHP's filter_var() already allows all kinds of email variations and you'll possibly never create a regular expression that's even close to the one they use.
The email validation I use looks like the following (applied to your code):
<?php
if (isset($scrubbed["email"])) {
// #see http://stackoverflow.com/a/574698/1251219
if (strlen($scrubbed["email"]) > 254) {
echo "The email address is too long: it must be 254 or less.";
}
// Validate syntax with PHP.
if (($email = filter_var($scrubbed["email"], FILTER_VALIDATE_EMAIL)) === false) {
echo "The email address has an invalid syntax.";
}
// Validate DNS reachability.
$host = substr($email, strrpos($email, "#") + 1) . ".";
if (!checkdnsrr($host, "A") && !checkdnsrr($host, "AAAA") && !checkdnsrr($host, "MX")) {
echo "The email address is unreachable.";
}
}
?>
Ever wondered what PHP's regular expression looks like?
/^(?!(?:(?:\x22?\x5C[\x00-\x7E]\x22?)|(?:\x22?[^\x5C\x22]\x22?)){255,})(?!(?:(?:\x22?\x5C[\x00-\x7E]\x22?)|(?:\x22?[^\x5C\x22]\x22?)){65,}#)(?:(?:[\x21\x23-\x27\x2A\x2B\x2D\x2F-\x39\x3D\x3F\x5E-\x7E]+)|(?:\x22(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x21\x23-\x5B\x5D-\x7F]|(?:\x5C[\x00-\x7F]))*\x22))(?:\.(?:(?:[\x21\x23-\x27\x2A\x2B\x2D\x2F-\x39\x3D\x3F\x5E-\x7E]+)|(?:\x22(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x21\x23-\x5B\x5D-\x7F]|(?:\x5C[\x00-\x7F]))*\x22)))*#(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-[a-z0-9]+)*\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-[a-z0-9]+)*)|(?:\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\]))$/iD
More info can be found at Comparing E-mail Address Validating Regular Expressions.
if ((!$email) && (!preg_match("/^[\w.-]+#[\w.-]+\.[A-Za-z]{2,6}$/", $email)))
should be
if ((!$email) || (!preg_match("/^[\w.-]+#[\w.-]+\.[A-Za-z]{2,6}$/", $email)))
...
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I convert ereg expressions to preg in PHP?
Escape string to use in mail()
I am trying send my form, but I get this error...
Deprecated: Function eregi() is deprecated
I tried replacing it with preg_match(), but no luck. Here is my code:
$all_valid = $name_valid = $email_valid = $comments_valid = true;
if (isset($_POST['submit'])) {
if ($_POST['name'] == '') {
$all_valid = $name_valid = false;
}
if ($_POST['comments'] == '') {
$all_valid = $comments_valid = false;
}
if (!$validator->check_email_address($_POST['email'])) {
$all_valid = $email_valid = false;
}
if ($all_valid) {
// #### NO PROBLEMS FOUND - PROCESS THE FORM DATA HERE
$mail_to = 'cat30#hotmail.com'; // recipient address
$subject = "Email from website"; // email message subject line
$name = mysql_real_escape_string(trim($_POST['name'])); // sanitize the name
if (eregi("\r",$name) || eregi("\n",$name)){ // avoid email header injection
die();
}
$mail_from = mysql_real_escape_string(trim($_POST['email'])); // sanitize their email address
if (eregi("\r",$mail_from) || eregi("\n",$mail_from)){ // avoid email header injection
die();
}
$comments = htmlspecialchars(trim($_POST['comments'])); // convert HTML characters into entities
$headers = 'From: '. $mail_from. "\r\n";
mail($mail_to, $subject, $comments, $headers);
$response = '<h2>Thanks for contacting us, will get back to you soon</h2>';
}
}
It returns a slightly different value than eregi but if I'm reading your code correctly you should be able to use the strpos() function to determine if a substring exists in a string. Eregi ignores case so you might have to combine this with a strtolower($string) call too.
Something like this:
if (strpos("\r",strtolower($name)) || strpos("\n",strtolower($name)))
Im new in php and this should be a easy to make, but I dont now how.
I want to check does $address has characters "#" and "."
<?php
function testEmail($address){
$a = strpos("/#/", $address);
$b = strpos("/./", $address);
if (($a != false) && ($b != false)) {
echo "Email is OK";
} else {
echo "Email is NOT OK";
}
}
testEmail("testmail#gmail.com");
?>
You can simply use filter_var to check validity of email.
$email = 'gaurang#gmail.com'
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Email correct
}
else {
//Email not correct
}
Is your question about this specific piece of code? Then #wroniasty's answer is correct.
But you really don't want to use a regex to test email validity, unless you want to use monstrosities like these.
However, if your question really is "How can I validate an email address?", then take a look at filter_var().
You can pass it the filter FILTER_VALIDATE_EMAIL, so it will validate the email address catching quite a bit of edge cases.
You can check an address using the following code:
if (filter_var($email_address, FILTER_VALIDATE_EMAIL)) {
// valid email
} else {
// invalid email
}
<?php
function testEmail($address) {
if (preg_match ( "/\.|#/", $address))
echo "Email OK";
else
echo "Email not OK";
}
?>
a better way to check for valid email address:
<?
function isValidEmail($email){
return preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $email);
}
?>
I know email validation is one of those things which is not the funniest thing on the block. I'm starting up a website and i want to limit my audience to only the people in my college and i also want a preferred email address for my user. So this is a two part question.
Is there a really solid php function out there for email validation?
Can I validate an email from a specific domain. I dont want to just check if the domain exists, because I know www.mycollege.edu exists already. Is there really anyway to validate that the user has a valid #mycollege.edu web address?
This is what I use:
function check_email_address($email) {
// First, we check that there's one # symbol, and that the lengths are right
if (!preg_match("/^[^#]{1,64}#[^#]{1,255}$/", $email)) {
// Email invalid because wrong number of characters in one section, or wrong number of # symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode("#", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if (!preg_match("/^(([A-Za-z0-9!#$%&'*+\/=?^_`{|}~-][A-Za-z0-9!#$%&'*+\/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$/", $local_array[$i])) {
return false;
}
}
if (!preg_match("/^\[?[0-9\.]+\]?$/", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2) {
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++) {
if (!preg_match("/^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$/", $domain_array[$i])) {
return false;
}
}
}
return true;
}
EDIT Replaced depreciated ereg with preg_match for PHP 5.3 compliance
If you really want to make sure its valid make your signup form send them an email with a URL link in that they have to click to validate.
This way not only do you know the address is valid (because the received the email), but you also know the owner of the account has signed up (unless someone else knows his login details).
To make sure it ends correctly you could use explode() on the '#' and check the second part.
$arr = explode('#', $email_address);
if ($arr[1] == 'mycollege.edu')
{
// Then it's from your college
}
PHP also has it's own way of validating email addresses using filter_var: http://www.w3schools.com/php/filter_validate_email.asp
This should work:
if (preg_match('/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])#mycollege.edu$/', $email)) {
// Valid
}
Read here
http://ru2.php.net/manual/en/book.filter.php
Or in short
var_dump(filter_var('bob#example.com', FILTER_VALIDATE_EMAIL));
this might be a better solution. many answered already, eventhough its little different.
$email = "info#stakoverflow.com";
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
echo $email ." is a valid email address";
} else {
echo $email ." is not a valid email address";
}
I hope this one has simple to use.
for any e-mail
([a-zA-Z0-9_-]+)(\#)([a-zA-Z0-9_-]+)(\.)([a-zA-Z0-9]{2,4})(\.[a-zA-Z0-9]{2,4})?
for php preg_match function
/([a-zA-Z0-9_-]+)(\#)([a-zA-Z0-9_-]+)(\.)([a-zA-Z0-9]{2,4})(\.[a-zA-Z0-9]{2,4})?/i
for #mycollege.edu
^([a-zA-Z0-9_-]+)(#mycollege.edu)$
for php preg_match function
/^([a-zA-Z0-9_-]+)(#mycollege.edu)$/i
PHP CODE
<?php
$email = 'tahir_aS-adov#mycollege.edu';
preg_match('/^([a-zA-Z0-9_-]+)(#mycollege.edu)$/i', $email, $matches);
if ($matches) {
echo "Matched";
} else {
echo "Not Matched";
}
var_dump($matches);
A simple function using filter_var in php
<?php
function email_validation($email) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
echo("$email is a valid email address");
} else {
echo("$email is not a valid email address");
}
}
//Test
email_validation('johnson123');
?>