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 regex :
^[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