Site icon Leonid Mamchenkov

Partial string replacement with fixed length in PHP

Today I came across one of those problems that look simple and straight forward at first, but then somehow consume a good part of an hour to solve.  I wanted to replace a part of the string (in the middle), with given character, without changing the length of the string itself.  Once scenario would be a credit card number, where I would want to replace all digits with an ‘x’, leaving only the first digit and the last four as they were.  I tried a number of approaches, including sscanf() and array_splice() ones.  My final version is below.  It might be somewhat longer than I expected, but I like the simplicity of it.

<?php
/**
 * Replace middle of the string with given char, keeping length
 *
 * <code>
 * print padString('1234567890123456', 1, 4, '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;
}
?>

P.S.: Chris posted an alternative solution. Please have a look.

Exit mobile version