Lay down strict rules
Do not allow the user to type the emails separated by some character like ;
or ,
or any other.
How to apply this?
In the form, create a single field where 1 single email will be typed.
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 he will type each of the emails.
When submitting the form, simply receive the array and validate each entry.
With this, you eliminate the process of using explode()
and all this complication.
To sort it out the way it is
If you want to continue the way you are doing, where the user type the emails separated by a semicolon, it is enough that at the time of $_POST
, make a explode normally as you are already doing.
This will cause the data to form an array.
With the array in hand, place it in a repeat loop that will validate the format of each string. The string that has no email format, discard.
If the user has typed a comma or other character instead of a semicolon, simply ignore it, as the user is responsible for correctly typing, since there is no rigid rule on data entry as suggested above.
If you want to give the user more "flexibidade", allow the user to enter with a comma ,
, bar /
or semicolon ;
.
In this case, the logic is, when receiving the $_POST, use str_replace()
to change everything that is comma or bar 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 didn’t test the code. I typed here directly according to what was coming to mind.
The blast doesn’t do that anymore?
– rray
Not exactly, when I did the test, he put in a single line email3,email4. I’m thinking of checking if the delimiter.
– user24136