Doubt preg_match PHP

Asked

Viewed 522 times

1

I need to make a preg_match to check whether a string meets the following conditions:

  1. Start with a letter: a-z;

  2. Contain only letters, number and characters ,, ., - and _;

Current code:

preg_match('/^[0-9]{1,}[a-z0-9.]*[a-z0-9]/', $_POST['login']);
  • 1

    If you should start with a letter, why put [0-9]{1,} at first?

2 answers

2


Understanding:

Start with a letter: a-z;

It should start with a letter of a to z lowercase. OK!

Contain only letters, number and characters ,, ., - and _;

As it does not provide a minimum number of characters after the first character that is required ("Must start with a letter..."), it is considered (as I understood) that from the second character onwards it is optional; but if it is, it must meet the above criteria.

Soon:

Within the criteria set out in the question, you could use this expression:

^[a-z][a-z\d_,\-.]*$

Explanation:

^             Delimita o início da string.
[a-z]         O primeiro caractere deve ser de "a" a "z" (minúsculas).
[a-z\d_,\-.]  Segundo caractere em diante.
              A partir do segundo caractere, pode ou não ter:
                 [a-z]  letras de "a" a "z" (minúsculas)
                 \d     números
                 _      underline
                 ,      vírgula
                 \-     hífen (escapado)
                 .      ponto
*             Quantificador que irá encontrar nada ou quantas ocorrências tiver
              a partir do segundo caractere.
$             Delimita o fim da string.

Example using a function:

<?php
function checa($str){

   return preg_match('/^[a-z][a-z\d_,\-.]*$/', $str);

}

// 0 = false, 1 = true
echo checa("a"); // 1
echo checa("1"); // 0
echo checa("h1-11,11,"); // 1
echo checa("Aa"); // 0
echo checa("1abc_"); // 0
echo checa("aaaaaaaa"); // 1
echo checa("a-----,"); // 1
echo checa("a-12,_#,"); // 0
echo checa(""); // 0
?>

To check, you can use a if:

<?php
if(checa("a")){
   // com o valor "a" irá entrar aqui.
   // significa que a string começa com uma letra minúscula
   // e atende ao critério da regex
   echo "passou";
}else{
   echo "não passou";
}
?>

Remembering that capital letters and accents will be considered invalid.

  • 1

    If I’m not mistaken, in square brackets, the dot needs no escape ([.] is the same as [\.], see), but the hyphen does. That is, [,-\.] is "the interval between characters , and .", that coincidentally has only the character - (beyond their own , and .), see. But if you change the order of the characters, the range is invalid and will only work if the hyphen escapes: see here the invalid regex and here the corrected version, with \-

  • 1

    True. All you had to do was escape the hyphen. Thanks!

1

Following your parameters, I made this code:

$strings = array(
    'uma string inválida',
    'uma string valida',
    '0uma string invalida',
    'uma string invalida !',
    'uma-string_valida.',
    '@ uma-string_invalida.'
);

foreach ($strings as $str) {
    if (preg_match('/^[^a-z]+|[^a-zA-Z\s\,\.\-\_]+/', $str))
        echo 'String COM caracteres inválidos: '.$str.'<br>';
    else
        echo 'String SEM caracteres inválidos: '.$str.'<br>';
}

Returns:

String WITH invalid characters: a string Inváhard-working

String WITHOUT invalid characters: a string validates

String WITH invalid characters: 0an invalid string

String WITH invalid characters: an invalid string !

String WITHOUT invalid characters: a-string_validate.

String WITH invalid characters: @ a-string_invalida.

Note the regular expression (Regex):

^[^a-z]+|[^a-zA-Z\s\,\.\-\_]+

Search anything other than a-z at the beginning of string:

^[^a-z]+

Or (|)

Anything other than the characters: a-z, A-Z (capital letters), \s (space), ,, ., - or _.

[^a-zA-Z\s\,\.\-\_]+

Outside of its parameters, I added the uppercase letters and the space. If not, just remove from the regular expression: ^[^a-z]+|[^a-z\,\.\-\_]+.

Browser other questions tagged

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