Set rigid rules
Do not allow the user to enter emails separated by any character such as ;
or ,
or any others.
How do I apply this?
In the form, create a single field where you will enter 1 single email.
Add a button to display a new field. In this new field another email will be typed. The idea is for each email, the user will click on this "add field" button, where you will enter each email.
When submitting the form, just receive the array and validate each entry.
With this, you eliminate the process of using explode()
and all this complication.
To resolve as it is
If you want to continue the way you are doing, where the user types emails separated by a semicolon, it is enough that when you redeem $_POST
, make a normal explode as you are already doing.
This will make the data an array.
With the array in hand, place it in a loop that will validate the format of each string. The string that does not have an email format discards.
If the user typed a comma or another character instead of a semicolon, simply ignore it, as the responsibility for typing correctly is the user, since there is no hard rule in data entry, as suggested above.
If you want to give more flexibility to the user, allow the user to enter commas ,
, bar /
or semicolon ;
.
In this case, the logic is, when receiving $ _POST, use str_replace()
to change everything that is comma or slash by semicolon.
Example
<?php
$error = null;
/**
Verifica se o dado foi postado e se não é vazio.
*/
if (isset($_POST['Emails']))
$emails = trim($_POST['Emails']);
if (empty($emails))
/**
Dados recebidos são inválidos.
*/
$error = 1;
/**
Prossegue com as execuções caso não exista erros prévios.
*/
if (empty($error))
{
/**
Substitui vírgula e barra por ponto e vírgula
*/
$emails = str_replace( [',','/'], ';', $emails);
/**
Explode o caracter delimitador ;
*/
$arr = explode(';', $emails);
/**
Verifica se o explode realmente gerou um array.
*/
if (is_array($arr))
{
/**
Itera o array
*/
foreach($arr as $v)
{
/**
Verifica se possui formato de email.
*/
if (ValidMailAddress($v))
$data[] = $v;
}
}else
/**
Não foi possível montar o array.
*/
$error = 2;
}
/**
Caso exista erro, exibe o código do erro.
Isso é para depuração. Obviamente, não deve exibir dessa forma grotesca ao usuário.
*/
if (!empty($error))
echo 'error: '.$error;
else{
if (isset($data) && is_array($data))
/**
Exibe o resultado do array final
*/
print_r($data);
else
echo 'Nenhum email válido foi encontrado.';
}
/**
Valida o formato da string.
A expressão regular verifica que se a string possui formato de email.
Note que validar o formato da string não quer dizer que o email exista ou seja válido.
*/
function ValidMailAddress($str)
{
$rule = '/^([0-9,a-z,A-Z,_,-,.]+)([.,_,-]([0-9,a-z,A-Z,_,-,.]+))';
$rule.= '*[@]([0-9,a-z,A-Z]+)([.,-]([0-9,a-z,A-Z]+))';
$rule.= '*[.]([0-9,a-z,A-Z]){2}([0-9,a-z,A-Z])?$/';
return (preg_match($rule, $str)? true : false);
}
?>
obs: I did not test the code. I typed here directly as the mind arose.