If I understand you want the preg_match
valide if it contains only the following types of characters:
- traces
- dots
- bars
- sign of
+
- sign of
-
- commas
- spaces
- numbers
- letters
#
(hash)
*
(asterisk)
You can use the following regex:
^[a-z0-9\-+, .\#*\\/]+$
In the 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:
- o the keys
[...]
and everything inside them will be accepted (will do the "match")
- the sign of
^
indicates that you should start with exactly the following expression
- the sign of
$
indicates that it should end exactly with the previous expression
- The sign of
+
between the ]
and the $
(...]+$
) indicates that it must have the format of what is inside [...]
until it finds the next expression, as it has no expression, only the $
then ends there, (regardless of the amount of characters)
Extra explanations:
- the
a-z
indicates that it may contain from A to Z
- the
\d
indicates that it can contain from 0 to 9 (is equivalent to typing 0-9
)
- The
\-
indicates that it may contain hyphens (dash -
), the bar is to escape and not mix with some expression shortcut
\\
is to accept inverted bars, use two bars so that the regex does not think you are trying to escape the next expression
- The
i
in #...#i
is to consider both uppercase and minuscule letters
^[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
This seems a little vague. What is the format of the input data ? It does not matter the order of the characters to accept ?
– Isac
this is for a textarea form... if the user inserts other characters than the ones I mentioned, the error.
– Jonnhypi
Could you help? It’s for school :D
– Jonnhypi