Jun
24
PHP Regex Extract Username from Email Address
June 24, 2008 |
You can use the following PHP snippet to grab the username out of an e-mail address. Given coldwarkids@ussr.com, the result will be coldwarkids.
This expression works to extract a username from an e-mail address because it gets everything up to the @ in one group and holds everything including and after the @ to the end of the line in another group. In the expression, after separating the two groups, it simply drops the second group so everything after @ goes nowhere.
<html>
<head><title>Extracting usernames from email addresses</title></head>
<style>
.err { color : red ; font-weight : bold }
</style>
<body>
<form action="<?= $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="input" /><br/>
<input type="submit" value="Submit Form" /><br/><br/>
<?php
if ( $_SERVER['REQUEST_METHOD'] == "POST" )
{
$input = $_POST['input'];
if (preg_match ( "/^([^@]+)(@.*)$/", $input ) )
{
# Do some processing here - input if valid
$username = preg_replace( "/^([^@]+)(@.*)$/", "$1", $input);
print "<b>Found username \"$username\"</b>";
}
else
{
print "<span class=\"err\">No username found here:</span><br/>";
}
}
?>
</form>
</body>
</html>
Regular Expression Explanation:
|
^ |
the beginning of the line … |
|
( |
a capturing group containing … |
|
[^@] |
everything that isn’t an at (@) sign … |
|
+ |
found one or more times, up to … |
|
( |
another group containing … |
|
@ |
|
|
. |
any character |
|
* |
found zero, one, or many times … |
|
) |
the end of the group … |
|
$ |
the end of the line. |
Similar Posts
- PHP Regex - Validate Email Address
- PHP Regex Validate IP address
- PHP Regex Extract Directiory from Full Path
- PHP Regex - Extract Filenames from Full Path
- PHP Regex Extract Filename from Full Path
- Validate URL Using PHP Regex
- PHP Regex Remove Whitespace from HTML


































