# PHP: String Mask

**URL:** <https://forum.kirupa.com/t/php-string-mask/175595>\
**Category:** open source\
**Created:** [January 16, 2006, 6:54am UTC](https://forum.kirupa.com/t/php-string-mask/175595 "2006-01-16T06:54:46Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Jeff\_Wheeler](https://avatars.discourse-cdn.com/v4/letter/j/59ef9b/32.png) [@Jeff\_Wheeler](https://forum.kirupa.com/u/Jeff_Wheeler)\
**Post date:** [January 16, 2006, 6:54am UTC](https://forum.kirupa.com/t/php-string-mask/175595/1 "2006-01-16T06:54:46Z")

</div>

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:

```php
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):

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

```

Use it like this:

```php
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 🙂

**Edit** : Noted harish’s PHP4 compatibility suggestion.
