First of all, I would like to say that the reason your example fails is not the space. It is the lack of '.' in former part and lack of '@' in the latter part.
If you input
'someone@example.co m'
or 's omeone@example.com'
, it will success.
So you may need 'begin with' and 'end with' pattern to check strictly.
There is no exist method to check where a regular expression match fails as I know since check only gives the matches, but if you really want to find it out , we can do something by 'break down' the regular expression.
Let's take a look at your example check.
preg_match ("/^[\w\-]+\@[\w\-]+\.[\w\-]+$/",'someone@example.com.');
If it fails, you can check where its 'sub expression' successes and find out where the problem is:
$email = "someone@example.com.";
if(!preg_match ("/^[\w\-]+\@[\w\-]+\.[\w\-]+$/",$email)){ // fails because the final '.'
if(preg_match("/^[\w\-]+\@[\w\-]+\./",$email,$matches)){ // successes
$un_match = "[\w\-]+"; // What is taken from the tail of the regular expression.
foreach ($matches as $match){
$email_tail = str_replace($match,'',$email); // The email without the matching part. in this case : 'com.'
if(preg_match('/^'.$un_match.'/',$email_tail,$match_tails)){ // Check and delete the part that tail match the sub expression. In this example, 'com' matches /[\w\-]+/ but '.' doesn't.
$result = str_replace($match_tails[0],'',$email_tail);
}else{
$result = $email_tail;
}
}
}
}
var_dump($result); // you will get the last '.'
IF you understand the upper example, then we can make our solution more common, for instance, something like below:
$email = 'som eone@example.com.';
$pattern_chips = array(
'/^[\w\-]+\@[\w\-]+\./' => '[\w\-]+',
'/^[\w\-]+\@[\w\-]+/' => '\.',
'/^[\w\-]+\@/' => '[\w\-]+',
'/^[\w\-]+/' => '\@',
);
if(!preg_match ("/^[\w\-]+\@[\w\-]+\.[\w\-]+$/",$email)){
$result = $email;
foreach ($pattern_chips as $pattern => $un_match){
if(preg_match($pattern,$email,$matches)){
$email_tail = str_replace($matches[0],'',$email);
if(preg_match('/^'.$un_match.'/',$email_tail,$match_tails)){
$result = str_replace($match_tails[0],'',$email_tail);
}else{
$result = $email_tail;
}
break;
}
}
if(empty($result)){
echo "There has to be something more follows {$email}";
}else{
var_dump($result);
}
}else{
echo "success";
}
and you will get output:
string ' eone@example.com.' (length=18)