PHP (Preg_match)

1

I would like you to help define my preg_match .

This will be for the creation of a form textarea $_POST['text'] .

I want pregmatch to just accept: Traces, Dots, Bars, + and -, commas, spaces, numbers, letters, # and *.

preg_replace("", $data);
    
asked by anonymous 16.04.2018 / 21:20

1 answer

2

If you understand, you want the preg_match to validate if it contains only the following character types:

  • Strokes
  • points
  • bars
  • sign of +
  • sign of -
  • commas
  • spaces
  • numbers
  • lyrics
  • # (hash)
  • * (asterisk)

You can use the following :

^[a-z0-9\-+, .\#*\/]+$

No preg_match would be:

if (empty($_POST['text'])) {
    echo 'Não digitou nada';
} else {
    $text = $_POST['text'];

    if (preg_match('#^[a-z0-9\-+, .\#*\/]+$#i', $text)) {
        echo 'Validou';
    } else {
        echo 'Não validou';
    }
}

Explaining the regex

This regex is very simple:

  • the [...] keys and everything inside will be accepted (will match)
  • The ^ sign indicates that it should begin exactly with the following expression
  • the sign of $ indicates that it should end exactly with the previous expression
  • The sign of + between ] and $ ( ...]+$ ) indicates that it should have the format of what it has within [...] until it finds the next expression, since it has no expression, only $ then ends there, (regardless of the number of characters)

Extra explanations:

  • a-z indicates that it can contain from A to Z
  • \d indicates that it can contain 0 to 9 (is equivalent to typing 0-9 )
  • The \- indicates that it may contain hyphens ( - ), the bar is to escape and not mix with any shortcut
  • \ is to accept backslashes, use two bars so that regex does not think you are trying to escape the next expression
  • The i in #...#i is to consider both uppercase and lowercase
^[a-z\d\-+, .\#*\/]+$
^  ^                ^^
.  .                ..
.  .                .... Termina exatamente com a expressão anterior
.  .                .
.  .                .... busca até o "final" ou até a próxima expressão
.  .
.  ..................... tudo que estiver dentro de '[...]' será valido
.
........................ deve começar exatamente com a próxima expressão
    
16.04.2018 / 21:48