Check if there is a character within a text

2

I have the following code:

if($_POST['Submit'] == "Enviar"){   
    $explodir = explode(";",$_POST['Emails']);
    foreach($explodir as $exp){
        echo $exp."<br>";
    }   
}
<form method="post" name="form">
<textarea rows="10" cols="80" name="Emails"></textarea>
<input type="submit" name="Submit" value="Enviar">
</form>

The goal is for users to send e-mails separated by a semicolon: email1; email2; email3; etc ... however how would I delete e-mails that do not contain a semicolon? Ex: email1; email2; email3; email4;

    
asked by anonymous 13.10.2015 / 19:23

3 answers

4

You can use preg_split() which creates an array based on a delimiter is a regular expression.

[^\w@\.] It means combine anything other than letters ([a-zA-Z), numbers ([0-9]) that is set with \W , @ , and \. are exceptions added.

[^] this is denied list ie it will not capture the characters inside it.

<?php
   $str = 'email1#email2%email3,email4@[email protected];_webmail.com';
   $arr = preg_split('/[^\w@\.]+/', $str);

Output:

Array
(
    [0] => email1
    [1] => email2
    [2] => email3
    [3] => email4@[email protected]
    [4] => _webmail.com
)
    
13.10.2015 / 19:34
4

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.

    
13.10.2015 / 20:25
0

Responding directly, as the title of your question:

if ($_POST['Submit'] == "Enviar") {   
    $explodir = explode(";", $_POST['Emails']);
    foreach ($explodir as $exp) {
        if (strpos($exp, ',') !== false) {
            $exp = explode(",", $exp);
        }
        echo $exp."<br>";
    }   
}

Note the following excerpt:

  

if (strpos ($ exp, ',')! == false) {

     

$ exp = explode (",", $ exp);

     

}

The function strpos () finds the first position of the character of your choice. It is faster too, including regular expressions or even strstr (), follows the function link: link

Note: Always compare to the search with === false or! == false, strpos has varying returns in case of false or empty return.

    
13.10.2015 / 22:40