Thursday, April 3, 2008

php: Cleaning user input text (some text manipulation)

There are many times you will want to ask a user for text input. One of the more common usages is in a search. And usually you will take the word and use it to make a query. But for now, it is important that the code be "cleaned" so that frivolous mistakes go unnoticed by the system (e.g. the user puts a space between words). Also, we are going to take words separated by spaces and make them their own words by putting them in an array.

This snippet does the following:
1) ereg_replace - replaces all the commas with spaces in the $text variable
2) strtolower - makes the whole string lowercase,
3) eregi_replace - replaces anything that isn't a number, letter, space, or apostrophe
4) preg_replace - replaces multiple spaces with 1 space
5) trim - trims the spaces from the sides
6) explode - "explodes" the string into an array delimited by spaces


//*MANIPULATE STRING****************************************************
$cleaned_text = explode(' ',trim(preg_replace('/[\s\s+]/', ' ', eregi_replace("[^a-z0-9 ']", "", strtolower(ereg_replace("[,]"," ",$text))))));

No comments: