Jump to content

Beginner here...can't get strlen to work right


dmaar

Recommended Posts

Hey all, new guy here.  I just started learning PHP this past week, but am having a little trouble when trying to mess around with it.

 

Basically I have a page with an order form on it that has a few sections for input.  One of those is a phone number text box.  I want the page to return an error message when the string length is not equal to 12 (in the format xxx-xxx-xxxx counting the hyphens).  No matter what I try I either always get the error message, or get it sometimes but not when I should.

 

Here's what I currently have:

if (strlen($phone != 12))
{
die ('You did not enter your phone number in the correct format.  Please press the back button on your browser and enter your phone number in the format ddd-ddd-dddd');
}

 

So that makes perfect sense in my mind...but obviously not to PHP. 

 

Any help would be appreciated, thanks.

Link to comment
Share on other sites

Ignore strlen and use regex, As someone could enter "I am coolaid" and it would validate.

$phone = '444-444-3444';
print strlen($phone); //Will print 12

//Ensure it is well formed.
if (!preg_match('/^[2-9]{1}[0-9]{2}-[0-9]{3}-[0-9]{4}$/', $phone)) {
    die('Phone number is NOT valid');
}

 

This will check if the phone number is valid and well conformed in '333-333-3333' format.

Link to comment
Share on other sites

Thanks for the help, it definitely works. 

 

I'd like to understand what exactly is going on in it though, could someone explain to me what the different parts of that string mean (as in all the numbers and the different sections in the parenthesis)? 

 

I think I understand some of it, like the [0-9] are to make sure that there is a valid number..but what about the {1} and {2} and so on?

 

 

Thanks again for the help.

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.