Me hdi
Me hdi

Reputation: 1912

Hide numbers of a phone number

How can I show and hide the some numbers of a phone number by replacing it with * like 0935***3256 by PHP?

EX:

09350943256 -> 0935***3256
09119822432 -> 0911***2432
09215421597 -> 0921***1597
...


$number = '09350943256';
echo str_pad(substr($number, -4), strlen($number), '*', STR_PAD_LEFT);

Top php code result is as: *******3256 but i want result as: 0935***3256

How is it?

Upvotes: 10

Views: 13315

Answers (6)

Jaber Al Nahian
Jaber Al Nahian

Reputation: 1061

In short:

$phone = 01133597084;
$maskedPhone = substr($phone, 0, 4) . "****" . substr($phone, 7, 4);

// Output: 0113****7084

Upvotes: 6

Mick
Mick

Reputation: 973

Instead of doing the math of calculating indices, I suggest this „declarative“ solution:

<?php

$number='0123456789';
$matches=[];
preg_match('/(\\d{4})(\\d+)(\\d{4})/', $number, $matches);
$result=$matches[1].str_repeat('*',strlen($matches[2])).$matches[2];
print($result);

?>

Upvotes: 0

karthikeyan K
karthikeyan K

Reputation: 13

You can use substr_replace() function

<?php
$mobnum ="09350943256";
for($i=4;$i<7;$i++)
{
  $mobnum = substr_replace($mobnum,"*",$i,1);
}
echo $mobnum;
?>

Upvotes: 1

ScaisEdge
ScaisEdge

Reputation: 133370

You could use substr and concat this way

to work for any $number with any number of n digit length

 <?php

     $number = "112222";
     $middle_string ="";
     $length = strlen($number);

     if( $length < 3 ){

       echo $length == 1 ? "*" : "*". substr($number,  - 1);

     }
     else{
        $part_size = floor( $length / 3 ) ; 
        $middle_part_size = $length - ( $part_size * 2 );
        for( $i=0; $i < $middle_part_size ; $i ++ ){
           $middle_string .= "*";
        }

        echo  substr($number, 0, $part_size ) . $middle_string  . substr($number,  - $part_size );
     }

The output if you make $number = "1" is * and if $number = "12" is *2 and for $number = "112222" is 11**22. and it goes on.

Upvotes: 15

Sinan Kayapınar
Sinan Kayapınar

Reputation: 1

<?php  
$phone='05325225990';

function stars($phone)
{
	$times=strlen(trim(substr($phone,4,5)));
	$star='';
	for ($i=0; $i <$times ; $i++) { 
		$star.='*';
	}
	return $star;
}

$result=str_replace(substr($phone, 4,5), stars($phone), $phone);
echo $result;

?>

0532*****90

Upvotes: 0

Qirel
Qirel

Reputation: 26450

You can use substr() to fetch the first 4 and last 4, and add four * in the middle manually, and put it all together in a string.

$phone = "09350943256";
$result = substr($phone, 0, 4);
$result .= "****";
$result .= substr($phone, 7, 4);
echo $result;

The above would output

0935****3256

Live demo

Upvotes: 0

Related Questions