简体   繁体   English

用x代替10位数字的前4位数字

[英]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: 我正在尝试将数字的前4位替换为X,例如:

$num= 1234567890

I want the output to appear like this: XXXX567890 我希望输出看起来像这样: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 ? 但是它只删除最后4位数字,那我该怎么办?

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 http://php.net/manual/zh/function.substr.php

With substr_replace function: 使用substr_replace函数:

$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 解决方案1: 在此处尝试此代码段

<?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 解决方案2: 在此处尝试此代码段

<?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 输出: XXXX567890

Another solution is to use str_pad which "fills up" the string to 10 elements with "X". 另一种解决方案是使用str_pad,用“ X”将字符串“填充”到10个元素。

$num= 1234567890;

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

https://3v4l.org/tKtB7 https://3v4l.org/tKtB7

Or if the string lenght is not always 10 use: 或者,如果字符串长度并非始终为10,请使用:

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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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