Jump to content
xisto Community
Sign in to follow this  
kvarnerexpress

Cleaning User Input With Regex

Recommended Posts

As anyone who works with user input knows, not everyone who submits information makes it look proper.

One one of my web forms, I parse all the needed fields that I wish to be title cased; their name, address, city, etc.

I use this to perform this action, which works nicely:

PHP Code:

$string = ucwords(strtolower($string));

This fixes the input if the user types in all caps or all lowercase. There is a problem I have been noticing about those who enter a generation after their name, such as "Bill Warner III".

The above function changes it to "Bill Warner Iii", which is incorrect. I have been toying with a regular expression to catch these I's (or sometimes V's) and turn them all uppercase, but to no avail. Here are versions of my non-working code:

PHP Code:


$string = preg_replace("/\b([IiVv])+\b/e", strtoupper("$1"), $string);$string = preg_replace("/\b([IiVv]+)\b/e", strtoupper("$1"), $string);$string = preg_replace("/\b([IiVv]+)$/e", strtoupper("$1"), $string)


Thanks,kivarnerexpress

Share this post


Link to post
Share on other sites

This pattern should match almost any Roman numeral below L/50 (it is unlikely you will ever encounter anything beyond, say, 10th/X generation names).

 

/\b(i+|i+[vx]*?|v[i]*?|x+[vi]*?)\b/ei

Here's a quick example (the names are, of course, randomly chosen). Note that the 'strtoupper()' function is being evaluated as PHP code and is enclosed in quotes.

 

<?php$names = array(   'john sMith iv',   'Richard jones Iiv',   'JOE NOBODY II',   'Viva vivi ixen ivan III',   'Person XI',   'person xv');$pattern = '/\b(i+|i+[vx]*?|v[i]*?|x+[vi]*?)\b/ei';for( $i=0;$i<count($names);$i++ ) {   $name = ucwords(strtolower($names[$i]));   $string = preg_replace($pattern, 'strtoupper("$1")', $name);   $names_p[$names[$i]] = $string;}print_r($names_p);?>

Outputs:

Array

(

    [john sMith iv] => John Smith IV

    [Richard jones Iiv] => Richard Jones IIV

    [JOE NOBODY II] => Joe Nobody II

    [Viva vivi ixen ivan III] => Viva Vivi Ixen Ivan III

    [Person XI] => Person XI

    [person xv] => Person XV

)


Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | 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.