PHP: String Mask

Although very, very simple, this is very useful. It can mask a string by returning the first argument with all the letters stripped out except those in char list:

function strmsk($haystack, $char_list,$cut_chars=false) {
	$haystack = str_split($haystack);
	$newstr = array();
	foreach($haystack as $letter) if((boolean)strpos($char_list,$letter)!==(boolean)$cut_chars) $newstr[] = $letter;
	return implode('',$newstr);
}

PHP5 only, though, because of str_split. Edit: Actually, with harish’s hack (he told me over IM), it’s compatible with PHP4, too. Replace the first line of the function with this (I didn’t edit the actual code, because I feel this is too much of a hack):

$haystack = preg_split("//", $haystack, -1, PREG_SPLIT_NO_EMPTY);

Use it like this:

echo strmsk('Hello World','aeiou'); // eoo
echo strmsk('Hello World','aeiou',true); // Hll Wrld
echo strmsk('Hello World','aeiou',false); // eoo (same as first)

If the third parameter is true (or evaluates to true when type-cast), the char list are the letters removed from the string. Otherwise, they’re the only ones left.

This is really useful in money. When stripping $40,000.00 to 40000.00, it is very easy to use.

I hope you like its simplicity :slight_smile:

Edit: Noted harish’s PHP4 compatibility suggestion.