Skip to content
Advertisement

Replace number and email with XXXX in a sentence using jQuery

I’d like to replace the numbers and email from the sentences.

Example

$message = “Hi this is john, my personal no is 1213456789 and my email address is john@gmail.com”.

Output:

Hi this is john, my personal no is 1213456789 and my email address is john@gmail.com

I want the Output to be like this:

Output:

Hi this is john, my personal no is XXXXXXX789 and my email address is XXXX@gmail.com

But I’m currently getting like this :

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX@gmail.com

function which I’m using now

function numbers1($str)
{
 if(($until = strpos($str, '@')) !== false)
 {
  $str = str_repeat('X', $until) . substr($str, $until);
 }
}

Thanks in advance.

Advertisement

Answer

$message = "Hi this is john, my personal no is 1213456789 and my email address is john@gmail.com";
$arr = explode(" ", $message);
foreach($arr as $key=>$val)
{   
    if(!preg_match ("/[^0-9]/", $val))
    {
        $val_new = "XXXXXXX".substr($val, -3);
        $arr[$key] = $val_new;
    }
    else if(strpos($val, "@")>0)
    {   
        $arr_email = explode("@", $val);
        $arr_email[0] = "XXXX";
        $val_new = implode("@", $arr_email);
        $arr[$key] = $val_new;
    }
}

$new_msg = implode(" ", $arr);
echo $new_msg;

UPDATE 2 :

$message = "Hi this is john, my personal no is 1213456789 and my email address is john@gmail.com";
    $arr = explode(" ", $message);
    foreach($arr as $key=>$val)
    {   
        if(!preg_match ("/[^0-9]/", $val))
        {
            $val_new = "XXXXXXX".substr($val, -3);
            $arr[$key] = $val_new;
        }
        else if(preg_match ("/^[a-z0-9_+-]+(.[a-z0-9_+-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*.([a-z]{2,4})$/", $val))
        {   
            $arr_email = explode("@", $val);
            $arr_email[0] = "XXXX";
            $val_new = implode("@", $arr_email);
            $arr[$key] = $val_new;
        }
    }

    $new_msg = implode(" ", $arr);
    echo $new_msg;
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement