簡體   English   中英

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

[英]Replacing First 4 digits of a 10 digit number with x

我正在嘗試將數字的前4位替換為X,例如:

$num= 1234567890

我希望輸出看起來像這樣:XXXX567890

我已經嘗試過該功能:

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

但是它只刪除最后4位數字,那我該怎么辦?

你可以在相反的地方使用

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

第二個參數說明字符串的起始點,奇偶校驗(正或負)說明方向。 正數表示字符串的右邊,負數表示字符串的左邊。

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

使用substr_replace函數:

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

我認為這對於實現期望的輸出會有所幫助。

解決方案1: 在此處嘗試此代碼段

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

解決方案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

輸出: XXXX567890

另一種解決方案是使用str_pad,用“ X”將字符串“填充”到10個元素。

$num= 1234567890;

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

https://3v4l.org/tKtB7

或者,如果字符串長度並非始終為10,請使用:

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

如果編寫了一個微型函數來執行這樣的任務。

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