Jump to content

Trying to do simple regex, but not getting it.


nakins

Recommended Posts

I have a html form that will transfer inputs into a pdf. This is an application for a school related program. So, it is just asking for things like names, address, grades, etc. The fields are simple single item inputs, like first name, mid, last name. I'm trying to limit input to just what you would expect. For example, "Bill" in the first name field, should just be a-zA-Z.  But, if I enter bill&, it gives it a pass. Maybe my logic is wrong or just my idea of this all is wrong. The code is as follows.  What I think I'm saying here is if the string matches any numbers or the special characters in the list, then it should fail and die.

 

$pat='^[0-9./\|#$%^&*()!~-={}<>?:]$';
            if(empty($_POST['first']) || ereg($pat,$_POST['first'])){
                die('Invalid input for first name field.');
            }else{
                $data['first']=$_POST['first'];
            }

 

Could someone give me a little direction here?

 

Link to comment
Share on other sites

I would start off by using preg instead of ereg, as ereg will not be included in the core of PHP 6 (it will only be available as an extension).

If you want $_POST['first'] to only have letters of the alphabet (a-zA-Z), you can simply pass $_POST['first'] through ctype_alpha as well as empty()...

 

$_POST['first'] = array('billy', 'BILLY', 'BilLy', '_billy', 'bill101', 'billy!', NULL, '0', FALSE, '', ' ');
foreach($_POST['first'] as $val){
   echo $val,(ctype_alpha($val) && !empty($val))? ' = Valid!<br />' : ' = Invalid!<br />';
}

 

Output:

billy = Valid!
BILLY = Valid!
BilLy = Valid!
_billy = Invalid!
bill101 = Invalid!
billy! = Invalid!
= Invalid!
0 = Invalid!
= Invalid!
= Invalid!
= Invalid!

Link to comment
Share on other sites

Thanks, I'll look to see if ctype thing will work. I don't know if it will work for eveything, however. Like email.

 

No, it won't work for email, as emails need more than simply [a-zA-Z] ;)

But for the firstname post, ctype_alpha() and !empty should work just fine.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.