[英]How can I remove digits from a number and replace it with letters in PHP?
考慮$number="1234567890";
如何獲得“gRkBDa7890”的結果前 6 位數字應替換為隨機大小寫字母,並且只有$number
的最后 4 位數字應相同。 $number
的值每次都會不同,但總是 10 位數字。 目的是從他們的電話號碼為每個用戶生成推薦/邀請代碼。
你可以試試這個
$number = "1122334455667788";
$masked = str_pad(substr($number, -4), strlen($number), ' ', STR_PAD_LEFT);
function generateRandomString($length = 10) {
return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length);
}
$genco = generateRandomString();
$reffcode = $genco.$masked;
$reffcode = str_replace(' ', '', $reffcode);
echo trim($reffcode);
並且為了不重復,您應該在數據庫中添加所有給定的推薦代碼
然后,當您將新的 reff 代碼提供給 other 時,您需要檢查它是否已注冊,如果為 true,則重新生成字符串,如果為 false,則提供生成的字符串
訣竅是首先將電話號碼的最后 4 個數字分開,然后創建一個新的 6 個字符長的小寫和大寫字母隨機字符串。 接下來,將兩者結合起來。
正如 Glossy Power 所說,您應該根據數據庫中的現有代碼檢查新創建的推薦代碼。 這是以 while 循環的形式完成的。 下面的代碼將執行此操作。
function referral_code($phone_number){
// Get last four digits from phone number
$last_four_digits = substr($phone_number, -4);
// Set continue to true for looping
$continue = true;
// Loop
while ($continue) {
// Accepted characters for first part of referral link
$input = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
// Initiate variable
$random_letters = '';
// Create 6 character random string
for ($i = 0; $i < 6; $i++) {
$random_letters .= $input[rand(0, strlen($input) - 1)];
}
// Combine new random string with last four digits
$referral_code = $random_letters.$last_four_digits;
// Check if the newly created referral code is present in database
$sql = "SELECT referral_code FROM table WHERE referral_code = '$referral_code' LIMIT 1";
$result = mysqli_query($connection, $sql);
// If number of returned rows is zero
if(mysqli_num_rows($result) == 0) {
// Set continue to false to stop loop
$continue = false;
// Return referral code
return $referral_code;
}
}
}
您可以像這樣啟動 function:
echo referral_code('0612345678');
這將返回一個 10 個字符的字符串,其中前 6 個字符是隨機的小寫和大寫字母,最后 4 個字符是 5678。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.