How to allow only numbers and dashes with preg_replace?

Asked

Viewed 5,128 times

2

I have a question regarding preg_replace, would like to know how could you do to allow only numbers, and hyphens (-).

My code is this::

$ola = preg_replace('/[^[:alnum:]_]/', '',$_POST['ola']);

How can I allow only numbers and hyphens?

3 answers

5


preg_replace is not to check but to remove, if you want to remove everything but numbers and hyphens do so:

$ola = preg_replace('/[^\d\-]/', '',$_POST['ola']);
  • ^ is denial
  • \d is any number
  • \- is hyphenated

That is something that is not number or hyphen.

If you want to validate, then you might want to preg_match:

if (preg_match('/^[\d\-]+$/', $_POST['ola']) > 0) {
    echo 'Só é permitido números e hifens';
} else {
    echo 'Validou!';
}

2

You can use a list by denying digits (\d) and the hyphen (-) anything married is replaced by nothing.

$str = "abaaksjjkdhaf 29023487 - 1kfksdjf";
echo preg_replace('/[^\d-]/i', '', $str);

Exit:

29023487-1

Example - ideone

1

Well, your doubt is not very clear and it seems to me to be a misconception.

The preg_replace is used to replace characters matching a given regex with some other value. That is, it makes no sense to use it to validate or something like.

I’m beginning to understand that allow is more connected to validate, in case the string whichever character that not be a number or a hyphen, I want it to be discarded.

In that case, the most appropriate function is preg_match. With it you can tell if the string complies with 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 is this regex ago?

^ - Take the beginning of the string

[0-9-] - Checks if it is a number from 0 to 9 or a hyphen ([0-9] may be replaced by [\d] also

+ - Ensures that the occurrence of the left (numbers or hyphens) is repeated at least once

$ - Take the end of the string

Look at this regex functioning with some examples.

Browser other questions tagged

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