Search code examples
phpsubstr

Replacing selected characters in a PHP string


I have a variable :

$var = '+44123456789';

And I want to replace the 3 characters, that are 3 characters from the end with X's so :

$var = '+44123XXX789';

I know I could use :

$var = substr($var, 0, 6) . 'XXX' . substr($var, -3);

But the issue I have is that $var can be of varying lengths.

How would I set up substr to make this work in the same way but on a variable of any length? (P.S. $var will always be at least 8 chars long.)


Solution

  • Try this

    $var = '+44123123789';
    
    echo substr($var, 0, strlen($var) - 6) . 'XXX' . substr($var, -3);//+44123XXX789
    
    $var = '+44123123789111';
    
    echo substr($var, 0, strlen($var) - 6) . 'XXX' . substr($var, -3);//+44123123XXX111
    

    see demo here