Simple php function to filter out unwanted text char types.

Just wrote a little function that will remove all char types from a string or text (if thats in the string) that are not given in the chars list. In my example I only wanted alpha chars and spaces. It also converts all to lower caps.

It walks through the given string using a substr function to locate the char to be evaluated. If the char is found in the given allowed string using a strstr function it will add it to the return string, else it will simply discard it. Before evaluation it also converts the val to a lowercap.

<?php

function cleanstr($s, $c, $l=true){
        $r='';
        $l=strlen($s);
        if($l){$s=strtolower($s);}
        for($i=0;$i<$l;$i++){
                $v=substr($s, $i, 1);
                if(strstr($c, $v)){ $r .=$v;}
        }
        return $r;
}

$string='abcdef $%%# Chris';
$chars=' abcdefhijklmnopqrstuvwxyz';
echo cleanstr($string, $chars);
?>

Prints out…

php ./test.php
abcdef  chris
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s