PHP - Any way to do this?

Hitman
Soldato
Joined
25 Feb 2004
Posts
2,837
Hi there,

Trying to create a script that replaces part of a given string with some character. For example:

$string = "Xtrm2Matt";

What I'd like to do is replace the 3rd, 4th and 5th characters with *, so it turns into Xt***Matt.

Ideally I'd like to create a function which returns the new string as I'll needing to use this around 3 times per script. The only snag is the string can be between 4 and 16 characters long (so perhaps an if statement to determine which characters to replace).

Any ideas on how to attempt this?

Cheers
 
It'd depend on the length (ideally). Perhaps something like:

if( 4 => $length < 6 ) replace 2nd/3rd/4th
if( 6 > $length < 9 ) replace 3rd/4th/5th
if( 9 > $length < 13 ) replace 5th/6th/7th
if( $length > 13 ) replace 6th/7th/8th

Cheers
 
Last edited:
PHP:
$string = 'blahblah';
$middle = floor(strlen($string) / 2);
$string[$middle-1] = $string[$middle] = $string[$middle+1] = '*';

that will whack 3 *s in the middle of any string. :p
 
Back
Top Bottom