String Filtering

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
alsaffar
Forum Newbie
Posts: 16
Joined: Sun Sep 29, 2002 12:03 pm

String Filtering

Post by alsaffar »

Hi there,

If I have a text box that the user will enter keywords to search a databse, then I want to filter his string according to the follwoing:

1. At least there is one non space character in the string.
2. No more than 1 space between the words in the string.
3. No space at the end of the string.
4. Make the string all lower case.

Lets say the string is: "I Want to be a PILOT "

How can I achieve my goal?
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

try

Code: Select all

<html><body><pre>
<?php
$str = "I Want to be a PILOT ";
// splitting the string at each "whitespace", the whole string, suppress emtpy substrings
$arr = preg_split('!\s!', $str, -1, PREG_SPLIT_NO_EMPTY);
// apply strtolower() to each element/substring of $arr
$arr = array_map('strtolower', $arr);

// test-output of all elements
print_r($arr);
?>
</pre></body></html>
can (of course) be done without PCRE (preg_split) but I like it...

http://www.php.net/manual/en/function.preg-split.php
http://www.php.net/manual/en/function.strtolower.php
http://www.php.net/manual/en/function.print-r.php
Post Reply