Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

php - How To Replace Some Characters With Asterisks

I have a simple task to do with PHP, but since I'm not familiar with Regular Expression or something... I have no clue what I'm going to do.

what I want is very simple actually...

let's say I have these variables :

$Email = 'john@example.com'; // output : ****@example.com
$Email2 = 'janedoe@example.com'; // output : *******@example.com
$Email3 = 'johndoe2012@example.com'; // output : ***********@example.com

$Phone = '0821212121'; // output : 082121**** << REPLACE LAST FOUR DIGIT WITH *

how to do this with PHP? thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You'll need a specific function for each. For mails:

function hide_mail($email) {
    $mail_segments = explode("@", $email);
    $mail_segments[0] = str_repeat("*", strlen($mail_segments[0]));

    return implode("@", $mail_segments);
}

echo hide_mail("example@gmail.com");

For phone numbers

function hide_phone($phone) {
    return substr($phone, 0, -4) . "****";
}

echo hide_phone("1234567890");

And see? Not a single regular expression used. These functions don't check for validity though. You'll need to determine what kind of string is what, and call the appropriate function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...