PHP replace everything between two symbols with something else - php

I'm trying to replace the domain name of email addresses, between # and . with ***
For example:
$email1 = info#mytestdomain.com
$email2 = info#mytestdomain.net
Need to be become
$email1 = info#***.com
$email2 = info#***.net
I know I can use the PHP preg_replace function but I'm not sure what regex I need to use in my case. So my question is, which regex should I use in my case to replace everything between # and . with ***?
Thanks

You can use this assertion based regex.
$eml = preg_replace('/#\K[^.]+/', '***', $eml);
Live Demo

Live demo
$email1 = "info#mytestdomain.com";
echo preg_replace("/(.*#)([^\.]+)(\..*)/","$1***$3",$email1);
Output:
info#***.com

You could use a positive lookahead also.
$email1 = "info#mytestdomain.com";
echo preg_replace("/[^#]+(?=\.)/","***",$email1);
Pattern Explanation:
[^#]+(?=\.) Matches any character but not of # one or more times only if the characters are followed by a literal dot.

Related

php preg replace include slash(/)

i use preg replace since my column database does not support "strange letters"
but after regex i need keep "/", in this code bellow "/" is always missing
in code bellow i need to get all letter complete
<?php
$jurnalName = "TL 110/90-12 K93-N02 AHM+";
$name = htmlspecialchars(htmlentities($jurnalName));
$name = preg_replace('/[^A-Za-z0-9|\- +]/', '', $name);
var_dump($name);
the result is always "TL 11090-12 K93-N02 AHM+" what i expecting is complete "TL 110/90-12 K93-N02 AHM+"
Add / to the list of chars you want to keep
<?php
$jurnalName = "TL 110/90-12 K93-N02 AHM+";
$name = htmlspecialchars(htmlentities($jurnalName));
$name = preg_replace('/[^A-Za-z0-9|\-\s\+\/]/', '', $name);
var_dump($name);
(I also changed the space for \s and scaped the plus +, its optional here but I think its a good practice for characters that have spetial meaning inside regex

php: preg_match failed with special character pattern

I have an issue with php regex. I have same regex in JS and it works. I don't know what is the problem.
this is the php code regex:
echo $password; // 9Gq!Q23Lne;<||.'/\
$reg_password = "/^[-_0-9a-záàâäãåçéèêëíìîïñóòôöõúùûüýÿæœÁÀÂÄÃÅÇÉÈÊËÍÌÎÏÑÓÒÔÖÕÚÙÛÜÝŸÆŒ0\d!##$%^&*()_\+\{\}:\"<>?\|\[\];\',\.\/\x5c~]{6,30}$/i";
if(isset($password) &&
(!preg_match($reg_password, $password) || !preg_match("#[a-z]#", $password) || !preg_match("#[\d]#", $password))
){
echo "you failed";
}
original password from html input:
9Gq!Q23Lne;<||.\'/\
it is the same value just before the $reg_password.
I have make a test using escape_string from mysqli method but it doesn't work too:
$password = $this->db->escape_string($password);
echo $password; // 9Gq!Q23Lne;<||.\'/\\
I don't know what is my problem because I have used regex101.com to test it and it works..
Any idea about that?
Thanks
In your pattern, you need to use single quote instead of double ;)
So it will be like this
$reg_password = '/^[-_0-9a-záàâäãåçéèêëíìîïñóòôöõúùûüýÿæœÁÀÂÄÃÅÇÉÈÊËÍÌÎÏÑÓÒÔÖÕÚÙÛÜÝŸÆŒ0\d!##$%^&*()_\+\{\}:\"<>?\|\[\];\',\.\/\x5c~]{6,30}$/i';
You don't need to call preg_match multiple times, just use lookahead to enforce your rules as in this regex:
^(?=.*?\d)(?=.*?[a-z])[-\wáàâäãåçéèêëíìîïñóòôöõúùûüýÿæœÁÀÂÄÃÅÇÉÈÊËÍÌÎÏÑÓÒÔÖÕÚÙÛÜÝŸÆŒ0\d!##$%^&*()+{}:"<>?|\[\];',./\x5c~]{6,30}$
RegEx Demo
Code:
$re = "`^(?=.*?\\d)(?=.*?[a-z])[-\\wáàâäãåçéèêëíìîïñóòôöõúùûüýÿæœÁÀÂÄÃÅÇÉÈÊËÍÌÎÏÑÓÒÔÖÕÚÙÛÜÝŸÆŒ0\\d!##$%^&*()+{}:\"<>?|\\[\\];',./\\x5c~]{6,30}$`mu";
$str = "9Gq!Q23Lne;<||.\'/\\";
if (!preg_match($re, $input)) {
echo "you failed";
}

How to extract Email & Name from Full Email text using PHP?

I have a string as
$email_string='Aslam Doctor <aslam.doctor#gmail.com>';
From which I want to extract Name & Email using PHP? so that I can get
$email='aslam.doctor#gmail.com';
$name='Aslam Doctor'
Thanks in advance.
As much as people will probably recommend regular expression I'd say use explode().
Explode splits the string up in several substrings using any delimiter.
In this case I use ' <' as a delimiter to immediately strip the whitespace between the name and e-mail.
$split = explode(' <', $email_string);
$name = $split[0];
$email = rtrim($split[1], '>');
rtrim() will trim the '>' character from the end of the string.
Using explode + list:
$email_string = 'Aslam Doctor <aslam.doctor#gmail.com>';
list($name, $email) = explode(' <', trim($email_string, '> '));
If you can use the IMAP extension, the imap_rfc822_parse_adrlist function is all you need.
/via https://stackoverflow.com/a/3638433/204774
text variable have one paragraph. two emails are included there. using extract_emails_from_string() function we extracts those mails from that paragraph.
preg_match_all function will return all matching strings with the regular expression from inputs.
function extract_emails_from_string($string){
preg_match_all("/[\._a-zA-Z0-9-]+#[\._a-zA-Z0-9-]+/i", $string, $matches);
return $matches[0];
}
$text = "Please be sure to answer the Please arun1#email.com be sure to answer the Please be sure to answer the Please be sure to answer the Please be sure to answer the Please be sure to answer the Please be sure to answer the arun#email.com";
$emails = extract_emails_from_string($text);
print(implode("\n", $emails));
This is what I use - works for email addresses with and without the angle bracket formatting. Because we are searching from right to left, this also works for those weird instances where the name segment actually contains the < character:
$email = 'Aslam Doctor <aslam.doctor#gmail.com>';
$address = trim(substr($email, strrpos($email, '<')), '<>');

PHP preg_replace() pattern, string sanitization

I have a regex email pattern and would like to strip all but pattern-matched characters from the string, in a short I want to sanitize string...
I'm not a regex guru, so what I'm missing in regex?
<?php
$pattern = "/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+#((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i";
$email = 'contact<>#domain.com'; // wrong email
$sanitized_email = preg_replace($pattern, NULL, $email);
echo $sanitized_email; // Should be contact#domain.com
?>
Pattern taken from: http://fightingforalostcause.net/misc/2006/compare-email-regex.php (the very first one...)
You cannot filter and match at the same time. You'll need to break it up into a character class for stripping invalid characters and a matching regular expression which verifies a valid address.
$email = preg_replace($filter, "", $email);
if (preg_match($verify, $email)) {
// ok, sanitized
return $email;
}
For the first case, you want to use a negated character class /[^allowedchars]/.
For the second part you use the structure /^...#...$/.
Have a look at PHPs filter extension. It uses const unsigned char allowed_list[] = LOWALPHA HIALPHA DIGIT "!#$%&'*+-=?^_\{|}~#.[]";` for cleansing.
And there is the monster for validation: line 525 in http://gcov.php.net/PHP_5_3/lcov_html/filter/logical_filters.c.gcov.php - but check out http://www.regular-expressions.info/email.html for a more common and shorter variant.
i guess filter_var php function can also do this functionality, and in a cleaner way.
Have a look at:
http://www.php.net/manual/en/function.filter-var.php
example:
$email = "chris#exam\\ple.com";
$cleanEmail = filter_var($email, FILTER_SANITIZE_EMAIL); // chris#example.com

Regex Get Email handle from Email Address

I have an email address that could either be
$email = "x#example.com"; or $email="Johnny <x#example.com>"
I want to get
$handle = "x"; for either version of the $email.
How can this be done in PHP (assuming regex). I'm not so good at regex.
Thanks in advance
Use the regex <?([^<]+?)# then get the result from $matches[1].
Here's what it does:
<? matches an optional <.
[^<]+? does a non-greedy match of one or more characters that are not ^ or <.
# matches the # in the email address.
A non-greedy match makes the resulting match the shortest necessary for the regex to match. This prevents running past the #.
Rubular: http://www.rubular.com/r/bntNa8YVZt
Here is a complete PHP solution based on marcog's answer
function extract_email($email_string) {
preg_match("/<?([^<]+?)#([^>]+?)>?$/", $email_string, $matches);
return $matches[1] . "#" . $matches[2];
}
echo extract_email("ice.cream.bob#gmail.com"); // outputs ice.cream.bob#gmail.com
echo extract_email("Ice Cream Bob <ice.cream.bob#gmail.com>"); // outputs ice.cream.bob#gmail.com
Just search the string using this basic email-finding regex: \b[A-Z0-9._%+-]+#[A-Z0-9.-]+.[A-Z]{2,4}\b
It will match any email in any text, and in your first string it will match the whole string, and in the second, only the part of the string that is e-mail.
To quickly learn regexp this is the best place: http://www.regular-expressions.info
$email = 'x#gmail.com';
preg_match('/([a-zA-Z0-9\-\._\+]+#[a-z0-9A-Z\-\._]+\.[a-zA-Z]+)/', $email, $regex);
$handle = array_shift(explode('#', $regex[1]));
Try that (Not tested)

Categories