Skip to content

Instantly share code, notes, and snippets.

@mamchenkov
Last active September 25, 2015 19:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mamchenkov/976387 to your computer and use it in GitHub Desktop.
Save mamchenkov/976387 to your computer and use it in GitHub Desktop.
Partial string replacement with fixed width in PHP. Useful for things like credit card numbers.
<?php
/**
* Replace middle of the string with given char, keeping length
*
* <code>
* print padString('1234567890123456', 0, 0, 'x');
* </code>
*
* @param string $string String to process
* @param integer $start Characters to skip from start
* @param integer $end Characters to leave at the end
* @param string $char Character to replace with
* @return string
*/
function padString($string, $start, $end, $char) {
$result = '';
$length = strlen($string) - $start - $end;
if ($length <= 0) {
$result = $string;
}
else {
$replacement = sprintf("%'{$char}" . $length . "s", $char);
$result = substr_replace($string, $replacement, $start, $length);
}
return $result;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment