Check if there is a character inside a text

Asked

Viewed 3,386 times

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 the e-mails separated by semicolons: Email1;Email2;email3; etc... but how would I delete the emails that do not contain semicolons? Ex.: Email1;Email2;email3,email4;

  • 1

    The blast doesn’t do that anymore?

  • Not exactly, when I did the test, he put in a single line email3,email4. I’m thinking of checking if the delimiter.

3 answers

4


Can use preg_split() creating 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 defined with \W, @ and \. are exceptions added.

[^] This is denied list or will not capture the characters inside it.

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

Exit:

Array
(
    [0] => email1
    [1] => email2
    [2] => email3
    [3] => email4@[email protected]
    [4] => _webmail.com
)
  • Right. Forgive my ignorance, but would your code replace any other characters by a semicolon? e.g., If a person puts email1Aemail2Bemail3@....

  • 1

    The delimiter is any character other than a letter or number, I added as exceptions: @, . and _. @Mark

  • Got it. To finish. To list the emails would put inside the foreach, right? Ex.: foreach($arr as $array){ ... }

  • 1

    Yes, the return is an array, @Jose..

  • It worked!! thanks rray.

4

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.

  • +1 for the first approach, nothing to be permissive even!

0

Answering 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 = explodes(",", $Exp);

}

The strpos() function finds the first position of the character of its choice. It is faster also, including regular expressions or even strstr(), follows the function link: http://php.net/strpos

Observing: Always compare in the search with === false or !== false, strpos has varied returns in case of false or empty returns.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.