Search code examples
phpsubstringsubstr

replacing all x numbers except last 4 within input value


I have an input that looks like this

<input value="{{gameAccount.getAccountNumber() }}" disabled name="accountNumber" type="text">

which displays:

123456789

but I want it to display

*****6789

I get confused when it is in input value in this particular case with gameAccount.getAccountNumber()

substr($something?, 0, -4) . '****';

How do I go about this? thanks in advance

I also saw substr_replace() function...


Solution

  • As @ficuscr points out this is a better one liner for this:

    $gameId = '123456789';
    $gameId = str_repeat('*', strlen($gameId) - 4) . substr($gameId, -4);
    

    There may be a more elegant way to do this but this will work:

    $gameId = '123456789';
    
    $gameIdLenToMask = strlen($gameId) - 4;
    $mask = str_pad('', $gameIdLenToMask, '*');
    
    $gameIdMasked = substr_replace($gameId, $mask, 0, $gameIdLenToMask);
    
    // Prints: "*****6789" 
    var_dump($gameIdMasked);
    

    For more information see the docs for str_replace and str_pad on php.net.