简体   繁体   中英

Replacing First 4 digits of a 10 digit number with x

I'm trying to replace the first 4 digits of a number with X, for example:

$num= 1234567890

I want the output to appear like this: XXXX567890

I have tried the function:

 $new = substr($num, 0, -4) . 'xxx';

but It only removes the last 4 digits so what should I do ?

You can use the same in opposite

$num= 1234567890;
$new = 'xxxx' . substr($num, 4);
echo $new;

second parameter tells about starting point for string and parity(positive or negative) tells about direction. positive number means to right of string and negative number means to left of string.

http://php.net/manual/en/function.substr.php

With substr_replace function:

$num = 1234567890;
print_r(substr_replace($num, 'XXXX', 0, 4));    // XXXX567890

I think this one can be helpful for achieving desired output.

Solution 1: Try this code snippet here

<?php
ini_set('display_errors', 1);
$num= 1234567890;
echo "XXXX".substr($num, 4);//concatenating 4 X and with the substring

Solution 2: Try this code snippet here

<?php
ini_set('display_errors', 1);
$num= 1234567890;
$totalDigits=4;
echo str_repeat("X", $totalDigits).substr($num, $totalDigits);// here we are using str_repeat to repeat a substring no. of times

Output: XXXX567890

Another solution is to use str_pad which "fills up" the string to 10 elements with "X".

$num= 1234567890;

Echo str_pad(substr($num,4), 10, "X",STR_PAD_LEFT);

https://3v4l.org/tKtB7

Or if the string lenght is not always 10 use:

Echo str_pad(substr($num,4), strlen($num), "X",STR_PAD_LEFT);

If have written a tiny function to do tasks like this.

function hide_details($str, $num = 4, $replace = 'x') {
    return str_repeat($replace, $num).substr($str, $num);
}
echo hide_details('1234567890');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM