Adil
Adil

Reputation: 3183

Parsing input from user in any order or format

I am having some trouble trying to figure out how to parse information collected from user. The information I am collecting is:

Following are some examples of how I may receive this from users:

I started off with explode function but I was left with a huge list of if else statements to try to see how the user separated the information (was it space or comma or slash or hypen)

Any feedback is appreciated.

Thanks

Upvotes: 0

Views: 64

Answers (2)

WhyNotHugo
WhyNotHugo

Reputation: 9926

You might want to use a few regular expressions:

  • One that looks for 5 numeric digits: [^\d]\d{5}[^\d]
  • One that looks for 2 numeric digits: [^\d]\d{2}[^\d]
  • One that looks for a single letter: [a-zA-Z]

[EDIT]

I've edited the RegExes. They now match every one of the presented alternatives, and don't require any alteration of the input string (which makes it a more efficient choice). They can also be run in any order.

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

It's easy enough. The ZIP code is always 5 digits, so a simple regex matching /\d{5}/ will work just fine. The Age is a number from 1 to 3 digits, so /\d{1,3}/ takes care of that. As for the gender, you could just look for an f for female and if there isn't one assume male.

With all that said, what's wrong with separate input fields?

Upvotes: 2

Related Questions