Replace number and email with XXXX in a sentence using jQuery - php

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.

try preg_replace()
$str = "Hi this is john, my personal no is 1213456789 and my email address is john#gmail.com";
$replacements[1] = 'X';
$replacements[0] = 'XXXX#';
echo preg_replace(array('/[0-6]/', '/[ a-z]{0,4}+#/'), $replacements, $str);
output :- Hi this is john, my personal no is XXXXXXX789 and my email address is XXXX#gmail.com

$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;

You're asking how to do this using jQuery, however your sample code is written in PHP. I'll answer your question with a PHP snippet as well.
The reason why your function isn't working is because you're replacing pretty much everything from the beginning of the string up to the position where the first '#' is found. Then you're adding as many 'X' as characters are until that position, followed by the rest of the string. To complicate things more, this won't work if two or more email addresses are found in your string.
This should do. You might need to tweak the regexes for both the phone numbers and the email addresses, though:
$message = "Hi this is john, my personal no is 1213456789 and my email address is john#gmail.com";
// get all phone numbers
preg_match('/\d{3,}/s', $message, $phones);
// get all email addresses
preg_match('/[a-z.-]+#[a-z.-]+/s', $message, $emails);
foreach ($phones as $phone)
{
$message = str_replace($phone, str_repeat('X', strlen($phone) - 3) . substr($phone, -3), $message);
}
foreach ($emails as $email)
{
$parts = explode('#', $email);
$message = str_replace($email, str_repeat('X', strlen($parts[0])) . '#' . $parts[1], $message);
}
// Hi this is john, my personal no is XXXXXXX789 and my email address is XXXX#gmail.com
echo $message;

Related

Reading information from CSS in PHP

I am creating a website where users shall be able to upload plugins with a file called 'info.css'. I want my PHP-file to be able to read out information from this file, for example the ID.
The 'info.css' file will contain something similar to:
/*
ID: test-preset;
Name: Test Preset;
*/
I want the ID and Name to get into separate strings, without the 'id:' or 'name:'.
Please write any solution you may will work. I have tried with following (but have gotten stuck on the way. Please note that the information in the 'info.css' file may appear in a different order, so for example it should work if the 'Name:' comes first.
$preset_inf = strtolower($preset_inf);
$preset_inf = explode('*/', $preset_inf);
$preset_inf = str_replace('/*', '', $preset_inf[0]);
$preset_inf = str_replace(' ', '', $preset_inf);
$preset_inf = explode(';', $preset_inf);
Regex?
$str = "/*
ID: test-preset;
Name: Test Preset;
*/";
preg_match_all("/(ID|Name):\s*(.*?)\;/s", $str, $m);
var_dump($m);
This will produce:
array(3) {
[0]=>
string(35) "ID: test-preset;
Name: Test Preset;"
[1]=>
string(11) "test-preset"
[2]=>
string(11) "Test Preset"
}
Matches anything between ID/Name and ;.
Edit noticed it could be the other way around too. Edited the code.
The output array will look slightly different but the part you want is in $m[2] array.
https://3v4l.org/iusmV
You can use regex to retrieve each variable, so:
preg_match( '/Name: (.*?);/', $css_file, $match );
$name = $match[1];
echo $name;
preg_match( '/ID: (.*?);/', $css_file, $match );
$id = $match[1];
echo $id;
Would return
Test Preset
test-preset
In case you need a more general solution, here is a regex that will parse a header with an arbitrary number of options along with their names:
$string = '/*
ID: test-preset;
Name: Test Preset;
*/';
$pattern = '/^(?!\/\*)([^:]+):([^:]+);$/mU';
preg_match_all($pattern, $string, $matches, PREG_SET_ORDER, 0);
$results = array();
foreach($matches as $match){
$results[$match[1]] = $match[2];
}
$results now contains an array with this structure:
[
"ID" => "test-preset",
"Name" => "Test Preset"
]
This has the benefit of being able to handle any number of "Header arguments".
Scalable solution.
$presetInfoItem = [];
$presetInfo = [];
$presetFile = "/*
ID: test-preset;
Name: Test Preset;
*/";
$fields = ['ID', 'Name'];
foreach ($fields as $field) {
$matchesCount = preg_match_all("#$field:(?'$field'[\w-\s]*);#", $presetFile, $presetInfoItem);
if ($matchesCount === 0 || $matchesCount === false) {
$presetInfo[$field] = "";
} else {
$presetInfo[$field] = trim($presetInfoItem[$field][0]);
}
}
var_export($presetInfo);
For your pleasure:
<?php
$css = '/*
ID: test-preset;
Name: Test Preset;
*/';
$css = str_replace("*/", "", $css);
$css = str_replace("/*", "", $css);
$css = str_replace(";", "", $css);
$css = trim($css);
$lines = explode("\n", str_replace("\r", '', $css));
if(!empty($lines)) {
foreach($lines as $i => $line) {
$vals = explode(":", $line);
$key = $vals[0];
$value = $vals[1];
echo '<div><b>'.$key.'</b>: '.$value.'</div>';
}
}
?>
Result is:
ID: test-preset
Name: Test Preset
Regex is not needed :)

how to get last values of email after the #

i am trying to determine the best way to determine whether an email address is an outlook or hotmail address.
i therefore need to collect the values after the #
i.e
testemail#outlook.com
caputure the #
however this will not work in all instance as
this email address is valid:
"foo\#bar"#iana.org
i read that a solution could be to explode it, i.e:
$string = "user#domain.com";
$explode = explode("#",$string);
array_pop($explode);
$newstring = join('#', $explode);
echo $newstring;
this solution seems bit long and only captures the first values
would really appreciate some help
if You explode This :
$string = "user#domain.com";
$explode = explode("#",$string);
it Will be :
$explode[0] = user
$explode[1] = domain.com
try to use array_reverse() ti pick the last value of email:
<?php
$email='exa#mple#hotmail.com';
$explode_email=explode('#',$email);
$reversed_array=array_reverse($explode_email);
$mailserver=explode('.',$reversed_array[0]);
echo $mailserver[0];
?>
You could always just keep it simple and test if either value exists in the string using strpos() or stripos().
if ( FALSE !== stripos($string, 'outlook') {
// outlook exists in the string
}
if ( FALSE !== stripos($string, 'hotmail') {
// hotmail exists in the string
}
I hope this will be easy for you to understand.
<?php
$emailAddress = 'mailbox#hotmail.com'; //Email Address
$emailStringArray = explode('#',$emailAddress); // take apart the email string.
$host = $emailStringArray[1]; //last string after # . $emailStringArray[0] = Mailbox & $emailStringArray[1] = host
if($host == "hotmail.com" || $host == "outlook.com"){
//matches to outlook.com or hotmail.com
}
else{
//Does not match to outlook.com or hotmail.com
}
I would recommend matching with a regular expression.
if (preg_match("/\#hotmail.com$/", $email)) {
echo "on hotmail";
} else if (preg_match("/\#outlook.com$/", $email)) {
echo "on outlook";
} else {
echo "different domain";
}
Additionally, if you want to capture full domain to variable, you can do it like this:
$matches = [];
if (preg_match("/^.*\#([\w\.]+)$/", $email, $matches)) {
echo "Domain: " . $matches[1];
} else {
echo "not a valid email address.";
}
Try this :
$emailAddress = 'example\#sometext\#someothertext#hotmail.com';
$explodedEmail = explode('#', $emailAddress);
$emailServerHostName = end($explodedEmail);
$emailServerNameExploded = explode('.', $emailServerHostName);
$emailServerName = $emailServerNameExploded[0];
echo $emailServerName;

PHP Repalce text tags with another value that i have in array

I have this text:
$text = "Welcome {name}, this is your email address: {email}";
I want to replace the {name} and {email} tags at once, not one by one using str_replace("{name}","John",$text)
I already have the replace output this way:
$values_to_replace = array('name'=>'John','email'=>'blabla#gmail.com');
How to make it work to repalce whole text from one shot using the given $values_to_replace ?
Here are several ways:
First here is strtr(). It takes an key=>value array and replaces all occurences of key with value.
$values = array('name'=>'John','email'=>'blabla#gmail.com');
$text = "Welcome {name}, this is your email address: {email}";
$replacements = array();
foreach ($values as $name => $value) {
$replacements['{'.$name.'}'] = $value;
}
var_dump(strtr($text, $replacements));
Second str_replace() supports array for both the $search and $replace arguments.
$values = array('name'=>'John','email'=>'blabla#gmail.com');
$text = "Welcome {name}, this is your email address: {email}";
$search = array_map(
function($placeholder) {
return '{'.$placeholder.'}';
},
array_keys($values)
);
var_dump(str_replace($search, $values, $text));
The third option is interesting, if you like to handle all {something} occurrences. This requires a regular expression and logic so preg_replace_callback is needed.
$values = array('name'=>'John','email'=>'blabla#gmail.com');
$text = "Welcome {name}, this is your email address: {email}";
$replacer = function($match) use ($values) {
if (isset($values[$match['name']])) {
return $values[$match['name']];
} else {
return '';
}
};
var_dump(preg_replace_callback('(\\{(?P<name>[a-z\d]+)\\})i', $replacer, $text));
Since you can change the array keys to match the text to replace, then it's this easy:
$values_to_replace = array('{name}'=>'John','{email}'=>'blabla#gmail.com');
$text = str_replace(array_keys($values_to_replace), $values_to_replace, $text);
Or as Sébastien has shown.
To answer your comment, there are several ways, Sébastien's being one. Here's another:
$search = explode(',', '{'.implode('},{', array_keys($values_to_replace)).'}');
$text = str_replace($search, $values_to_replace, $text);
str_replace can take arrays as parameters:
$text = "Welcome {name}, this is your email address: {email}";
$from = array("{name}", "{email}");
$to = array("John", "blabla#gmail.com");
$new_text = str_replace( $from , $to, $text );

I want to get the last email from string in PHP

I have a string like
<?php
$string = "
hello aaa#aaa.com , you are the best.
this email bbb#bbb.com my be fake
(i have question to ccc#ccc.com)
that's all";
?>
I want to detect the last email (what ever number of email equal any number) for example: ccc#ccc.com
<?php
function getLastEmail($_String)
{
$_RegVariables = "/[\._a-zA-Z0-9-]+#[\._a-zA-Z0-9-]+/i";
if (preg_match_all($_RegVariables, $_String, $_Matches))
{
$_Result = array();
$_RegResult = array_combine($_Matches[0], $_Matches[0]);
foreach($_RegResult as $key=>$value)
{
$_Result[] = $key;
}
}
return $_Result[ sizeOf( $_Result )-1 ];
}
$string = "
hello aaa#aaa.com , you are the best.
this email bbb#bbb.com my be fake
(i have question to ccc#ccc.com)
that's all";
$lastemail = getLastEmail($string);
echo $lastemail;
?>
Now $lastemail is ccc#ccc.com
Good luck.
Here is a quick solution, you may have to do some string clean up to remove characters (like '(' or ')') but this works if those aren't present.
<?php
$string = "
hello aaa#aaa.com , you are the best.
this email bbb#bbb.com my be fake
i have question to ccc#ccc.com
that's all";
$a = explode(' ', $string);
$aEmail = array();
foreach($a as $svar=>$sval)
{
if(preg_match('/^[^#]+#[a-zA-Z0-9._-]+\.[a-zA-Z]+$/', $a[$svar]))
$aEmail[] .= $a[$svar];
}
$sEmail_Last = array_pop($aEmail);
echo $sEmail_Last; // echo ccc#ccc.com
?>

How can I break an email address into different parts in php?

Basically what I want to do is display an email using javascript to bring the parts together and form a complete email address that cannot be visible by email harvesters.
I would like to take an email address eg info#thiscompany.com and break it to:
$variable1 = "info";
$variable2 = "thiscompany.com";
All this done in PHP.
Regards,
JB
list($variable1, $variable2) = explode('#','info#thiscompany.com');
$parts = explode("#", $email_address);
Assuming that $email_address = 'info#thiscompany.com' then $parts[0] == 'info' and $parts[1] == 'thiscompany.com'
You can use explode:
$email = 'info#thiscompany.com';
$arr = explode('#',$email);
$part1 = $arr[0]; // info
$part2 = $arr[1]; // thiscompany.com
$email = "info#thiscompany.com";
$parts = explode("#", $email);
Try this one before you roll your own (it does a lot more):
function hide_email($email)
{ $character_set = '+-.0123456789#ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
$key = str_shuffle($character_set); $cipher_text = ''; $id = 'e'.rand(1,999999999);
for ($i=0;$i<strlen($email);$i+=1) $cipher_text.= $key[strpos($character_set,$email[$i])];
$script = 'var a="'.$key.'";var b=a.split("").sort().join("");var c="'.$cipher_text.'";var d="";';
$script.= 'for(var e=0;e<c.length;e++)d+=b.charAt(a.indexOf(c.charAt(e)));';
$script.= 'document.getElementById("'.$id.'").innerHTML=""+d+""';
$script = "eval(\"".str_replace(array("\\",'"'),array("\\\\",'\"'), $script)."\")";
$script = '<script type="text/javascript">/*<![CDATA[*/'.$script.'/*]]>*/</script>';
return '<span id="'.$id.'">[javascript protected email address]</span>'.$script;
}
How about a function for parsing strings according to a given format: sscanf. For example:
sscanf('info#thiscompany.com', '%[^#]#%s', $variable1, $variable2);

Categories