user1938653
user1938653

Reputation: 609

Parsing using preg_match

I have the following code:

    if(isset($_POST['login'])){

    $check = $_POST['theemail'];
    if (preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $check)){ 

    echo 'Email is valid ';
    }  

    }

        <form method="post" action="" autocomplete="off"> 


    <p align="right">Email <BR><input type="text" name="theemail" size="20" /></p>
    <p align="right"><input type="submit" name="register" value="Register" /></p>
    <p align="right"><a href="index.php">register</a></p>

   </form>

This code checks if an email is in a valid format ([email protected]) when a user submits a form, and it works; my problem is, is that when I try to get certain contents from the preg_match to be echoed to the user when submitting the form.

For example: the user has submitted the following e-mail: [email protected]

I'd like that the user will see in return: echo' Hello john(instead of john it'll be a variable $, or something that will display it). Your email's host is: gmail.com(instead of gmail it'll be a variable $ or something that will display it).

I tried to create divs around certain spots in my code in order to display them later in an echo, but i didnt succeed. Any help will be appriciated!

Upvotes: 0

Views: 215

Answers (1)

Veda
Veda

Reputation: 2073

I would have done it like this:

<?php
if(isset($_POST['register'])){
$check = $_POST['theemail'];
if (preg_match("/^([_a-z0-9-]+(\.[_a-z0-9-]+)*)@([a-z0-9-]+(\.[a-z0-9-]+)*)(\.([a-z]{2,3}))$/", $check, $match)){ 
echo 'Hello ' . $match[1] . ' your email address domain is '. $match[3] . '.' . $match[6];
} else {
echo 'Error, you entered an invalid email address';
}
}
?>

<form method="post" action="" autocomplete="off"> 
<p align="right">Email <BR><input type="text" name="theemail" size="20" /></p>
<p align="right"><input type="submit" name="register" value="Register" /></p>
<p align="right"><a href="index.php">register</a></p>
</form>

This would output:

Hello john your email address domain is doe.com

or, if the email address was invalid:

Error, you entered an invalid email address

And in all cases, it will show the form again.

Upvotes: 1

Related Questions