CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

Home: Perl Programming Help: Regular Expressions:
limit and replace characters



Dec 5, 2001, 9:59 PM

Post #1 of 5 (12647 views)
limit and replace characters Can't Post

I need to verify data as input into a form field.

The criteria is: any alphabetical letter, numeral, the dash or the underscore character is OK FINE - but periods, symbols, leading or trailing whitespace, and other punctuation must be removed (stripped out totally leaving valid characters only)

so: "ab-cd_ef" would be OK as is
but: " Ab._@c,D. -!'_g1" would become "ab_cd-ef_g1" (lower case)

whitespace between characters would be replaced with an underscore _ , but leading or trailing whitespace would be stripped totally

so: "ab cd" woud become "ab_cd"

and to make it trickier - the first and last characters cannot be anything other than a numeral or alpha character -

so: "_abcd123-" even though it contained all valid characters, would need to become "abcd123"

I admit - this is way over my head. I appreciate all assistance and explanations so I might learn something from this little problem.


Dec 5, 2001, 11:55 PM

Post #2 of 5 (12641 views)
Re: limit and replace characters [In reply to] Can't Post

Try this:

$str = q{ Ab._@c,D. -!'_g1-}; 

$str =~ s/\s/_/g; # replace whitespace with underscore
$str =~ s/[^\w-]+//g; # eliminate illegal characters
$str =~ s/^[-_]+//; # strip leading dashes/underscores
$str =~ s/[-_]+$//; # strip trailing dashes/underscores
$str = lc $str; # make the string lowercase

Hope it helps.

-- Marcus



Dec 6, 2001, 12:00 AM

Post #3 of 5 (12641 views)
Re: limit and replace characters [In reply to] Can't Post

Hmm. Untested and with a lot of room for improvements, corrections and optimizations:

# Lowercase 
$string = lc $string;
# Get rid of unwanted chars
$string =~ tr/a-z0-9_- //c;
# Remove leading and trailing Whitespace
$string =~ s/^\w*(.*?)\w*$/$1/;
# Replace remaining whitespace with underscores
$string =~ tr/ /_/;
# Check the last and first character
$string =~ s/^[^a-z0-9]*(.*?)[^a-z0-9]*/$1/;


Dec 6, 2001, 12:02 AM

Post #4 of 5 (12639 views)
Re: limit and replace characters [In reply to] Can't Post

Damn, I knew yours would be shorter and more beautiful ;-)


Dec 6, 2001, 1:03 AM

Post #5 of 5 (12638 views)
Re: limit and replace characters [In reply to] Can't Post

Geez, Marcus - you made that look easy.

(I bungled that for a week.)

Thank you, gentlemen, for the assistance. I shall memorize these lines and hopefully store this tidbit in my brain for later. I think I had four miles of code to get rid of any possibly funky punctuation characters... all error-ridden.


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives