Home > All, PHP, Web > Masking fixed length strings in PHP.

Masking fixed length strings in PHP.

A particular problem came up in the office today, masking of credit card numbers. As my friend Leonid has pointed out, one would think that this is a very simple task for any programmer. Or not.

Having read Leonid’s solution, and finding a comment on php.net which would also mask everything but the first and last four digits of a credit card number, I still felt that I needed to throw something of my own together. So here it is:

<?php
/**
 * Mask part of a string
 *
 * <code>
 * echo maskString('4012888888881881', 6, 4, '*');
 * </code>
 *
 * @param	string	$s		String to process
 * @param	integer	$start	Number of characters to leave at start of string
 * @param	integer	$end	Number of characters to leave at end of string
 * @param	string	$char	Character to mask string with
 * @return	string
 */
function maskString($s, $start, $end, $char = 'X') {
	$middle = '';
	for ($i = 0; $i < strlen($s) - $start - $end; $i++) {
		$middle .= $char;
	}
	return preg_replace('/^(d{' . $start . '})(d+.)(d{' . $end . '})$/', '${1}' . $middle . '${3}', $s);
}
?>