PHP Mask a String

Quick function for masking an account number, credit card number, or whatever else.

function mask ( $str, $start = 0, $length = null ) {
	$mask = preg_replace ( "/\S/", "*", $str );
	if( is_null ( $length )) {
		$mask = substr ( $mask, $start );
		$str = substr_replace ( $str, $mask, $start );
	}else{
		$mask = substr ( $mask, $start, $length );
		$str = substr_replace ( $str, $mask, $start, $length );
	}
	return $str;
}

// Usage:
$string = '1234 5678 9123 45678';
echo mask($string,null,strlen($string)-4); // *************5678