2

I have a .txt file where I would like to find an EXACT match of a single email entered in a form.

The present directives (see below) I used, work for a standard form. But when I use it in conjunction with an AJAX call and jQuery, it confirms it exists by just finding the first occurrence.

For example:

If that person enters "bobby@" it says not found, good.

If someone enters their full Email address and it exists in the file, it says "found", very good.

Now, if someone enters just "bobby", it says "found", not good.

I used the following three examples below with the same results.

if ( !preg_match("/\b{$email}\b/i", $emails )) {

echo "Sorry, not found";

}

and...

if ( !preg_match( "/(?:^|\W){$email}(?:\W|$)/", $emails )) {

echo "Sorry, not found";

}

and...

if ( !preg_match('/^'.$email.'$/', $emails )) {

echo "Sorry, not found";

}

my AJAX

$.ajax({  
type: "POST",  
url: "email_if_exist.php",  
data: "email="+ usr,
success: function(msg){

my text file

Bobby Brown [email protected]
Guy Slim [email protected]
Slim Jim [email protected]

I thought of using a jQuery function to only accept a full email address, but with no success partly because I didn't know where to put it in the script.

I've spent a lot of time in searching for a solution to this and I am now asking for some help.

Cheers.

5
  • 1
    Bearing in mind this was posted 4+ years ago, is it still an issue? Did you ever find a solution, given your comments with kkhugs? Commented Mar 24, 2017 at 18:04
  • @SamOnela Given it's over 4 years old; TBH I can't remember that far to say what I ended up doing to fix it or if I gave up on it. My PHP skills weren't as good back then as they are now. Yet, I won't be pursuing that matter such as re-resting / debugging just to find out why that didn't work me. Plus, in light of the question/code I posted, and my further knowledge with databases that I learned some years after, I would have used a database for this, rather than a plain text file. Thanks for asking though. Curious though as to why you visited the question. Commented Mar 24, 2017 at 18:08
  • that makes sense. I get curious about what questions are unanswered, especially by members with such high reputation levels... Commented Mar 24, 2017 at 18:14
  • @SamOnela I understand. I upvoted the answer just now given it seems correct in its own right. I'd only be lying to myself and others if I were to accept it. I'm sure there was a reason back then for my not accepting the answer. I know what you mean about "loose ends" though; I don't care for them myself neither, cheers. Commented Mar 24, 2017 at 18:20
  • @SamOnela "especially by members with such high reputation levels" - My rep and experience weren't that high back then lol - After a while where a year or so went by and have gotten better, I stopped asking questions and went on helping people instead ;-) I forgot to mention that earlier. Commented Mar 24, 2017 at 18:26

6 Answers 6

1

Because your text file contains "bobby" in it, any regex such as you are suggesting will always find "bobby". I would suggest checking for the presence of the @ symbol BEFORE you run the regex, as any valid email will always have @ in it. Try something like this:

if (strpos($email,'@')) {
    if ( !preg_match("/\b{$email}\b/i", $emails )) {
        echo "Sorry, not found";
    }
}

EDIT: Looking at this 4 years later... I would make the regex match to the end of the line, using the m modifier to specify multiline so the $ matches newline or EOF. The PHP line would be:

if ( !preg_match("/\b{$email}$/im", $emails )) {
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, this helped me a lot. However when I tried to reverse the process in replacing !preg_match with preg_match and changing the echo to Found it, it didn't work if it did find the full email address. If I enter bobby@ it said it found it, which won't work. What would be the reverse/opposite of your suggestion?
Honestly, I can't see why that wouldn't work. Did you change anything else at the same time? Try just putting an else at the end of the if, instead of taking out the !. Then you can have a response for both cases.
I didn't change anything else. I did try an else statement but only works with an accompanying die. The echo won't work. Baffled as to why it's not working.
0

If you're just checking to see if the user exists, this should work:

$users = trim(preg_replace('/\s\s+/', ' ', $users));
$userArray = explode(' ', $users);
$exists = in_array($email, $userArray);

Where $users is referencing to the example file and $email is referencing to the queried e-mail.

This replaces all newlines (and double spaces) with spaces and then splits by spaces into an array, then, if the e-mail exists in the array, the user exists.

Hope I helped!

Comments

0

'/^'.$email.'$/' is quite close. Since you want the check being "true" only if the full email address is on the file you should include in the pattern the "limits" of the email: Whitespace before and end_of_the_line after if:

'/ '.$email.'$/'

(Yes, I've just changed ^ -start of line- for a whitespace)

Comments

0

If your text file filled with lines that every line ending with the email,

so you can regex with testing and match by your "email + end od line"

like that:

if( preg_match("/.+{$email}[\n|\r\n|\r]/", $textFileEmails) ) 
{
     /// code
}

Comments

0

The code would validate first using php core functions whether the email is correct or not and then check for the occurrence.

$email = '[email protected]';
$found = false;
//PHP has a built-in function to validate an email 
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
    //Grab lines from the file
    $lines = file('myfile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        //Grab words from the line
        $words = explode(" ", $line);
        //If email found within the words set the flag as true.
        if(in_array($email, $words)) {
            $found = true;
            //If the aim is only to find the email, we can break out here.
            break;
        }
    }
}
if(false === $found) {
    echo 'Not found!';
} else {
    echo 'Found you!';
}

Comments

0
+50

If you file is formatted as your example first_name, last_name, [email protected] it's really easy to break it up on load to search.

I don't know why you would use preg_match for this bit your if you were advised to use preg use it to verify the email address. You're better off using indexOf method in php (strpos) to search the file but the below method works for your fixed file format.

Object Orientated File Reader and searcher

class Search{
    private $users = array();
    public function __construct($password_file){
        $file = file_get_contents($password_file);
        $lines = explode("\n", $file);
        $users = array();
        foreach($lines as $line){
            $users = expode(" ", $line);
        }
        foreach($users as $user){
            $this->users[] = array("first_name" => $user[0], "last_name" => $user[1], "email" => $user[2])
        }
    }

    public function searchByEmail($email){
        foreach($this->users as $key => $user){
            if($user['email'] == $email){
                    // return user array
                    return $user;
                    // or you could return user id
                    //return $key;
            }
        }
        return false;
    }
}

Then to use

$search = new Search($passwdFile);
$user = $search->searchByEmail($_POST['email']);
echo ($user)? "found":"Sorry, not found";

Using preg_match to validate email then check

If you want to use preg and your own file search system.

function validateEmail($email) {
    $v = "/[a-zA-Z0-9_-.+]+@[a-zA-Z0-9-]+.[a-zA-Z]+/";

    return (bool)preg_match($v, $email);
}

then use like

if(validateEmail($_POST['email'])){
    echo (strpos($_POST['email'], $emails) !== false)? "found":"Sorry, not found";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.