0

I want to validate all the files that are being uploaded on my site through PHP. I am using regular expressions to compare the file contents but it doesn't seem to be working as I expect it to work. I want to accept files with 1 term per line only.

EXPECTED INPUT:
HP34930
HP09099
HP98899

UNACCEPTABLE INPUT:
HP89980 HP98798 HP09232
some other text
HP58089

Here is my code:

$texthandle = file($_FILES["textfile"]["tmp_name"]);
foreach ($texthandle as $textline)
{
    if (!preg_match("/(HP\d+){1}/", $textline))
    {
    echo "Incorrect file format. Please provide a text file with 1 term per line.";
            exit(0);
    }       
}

Could someone suggest why this isn't detecting the way I want it to?

I have also tried

if (!preg_match("/^(HP\d+){1}$/", $textline))

but it isn't working as I expect it to work.

Thanks for your help!

4
  • "isn't working" isn't a proper issue explanation. As well as "isn't working correctly". Only you know what "correctly" means. Commented Oct 30, 2013 at 3:55
  • I have made some edits to be less ambiguous. I hope that helps. Commented Oct 30, 2013 at 4:00
  • I took your code and it does work ideone.com/I1sRLt Commented Oct 30, 2013 at 4:04
  • @Mike W: the whole file is not. OP checks line by line and the result if the whole file is good or not Commented Oct 30, 2013 at 4:06

1 Answer 1

1

Not sure what not working is, but try:

$texthandle = file($_FILES["textfile"]["tmp_name"], FILE_IGNORE_NEW_LINES);

and then:

if (!preg_match("/^HP\d+$/", $textline))

or if there are only 5 digits allowed:

if (!preg_match("/^HP[\d]{5}$/", $textline))

If there is any whitespace at the end like spaces, tabs, etc. it will fail, so you can try trim() on $textline.

Sign up to request clarification or add additional context in comments.

9 Comments

Your regex is identical (by behaviour) to the OP's one
The difference is the ^ and $ characters; these check for the start and end of the line, respectively.
@Ed Cottrell: there are anchors in the second OP's attempt
@zerkms: Could work sort of the same, or not, but definitely not identical :) And, maybe it's not the regex?
@AbraCadaver: it's identical to /^(HP\d+){1}$/ from the question. If you see the differences between your and this one - please share.
|

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.