Well, your question is not very clear and it seems to me to be a mistake.
preg_replace
is used to replace characters that marry certain regex with some other value. That is, it makes no sense to use it to validate or something like that.
I understand that allow to be more strongly bound to validate , in case the string has any character / strong> a number or a hyphen, I want it to be discarded .
In this case, the most appropriate function is the preg_match
. With it you can find out whether the string satisfies this rule or not.
if (preg_match('/^[0-9\-]+$/', $_POST['ola'])) {
// É um valor válido, que só contém números e hifens... segue a vida
} else {
// deu ruim
}
And what does this regex do?
^
- Get the start of the string
[0-9-]
- Checks whether it is a number from 0 to 9 or a hyphen ( [0-9]
can be replaced by [\d]
also
+
- Ensures that the occurrence of the left (numbers or hyphens) is repeated at least once
$
- Get the end of the string
See this regex working with a few examples .