Last active
September 25, 2015 19:58
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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