How to only allow numbers and hyphens with preg_replace?

2

I'm having a question regarding preg_replace , I'd like to know how I could do to only allow numbers, and hyphens ( - ).

My code is as follows:

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

How can I do just numbers and hyphens?

    
asked by anonymous 17.02.2017 / 21:00

3 answers

4

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 hyphen
  •   

That is, anything that is not a number or a hyphen.

If you want to validate, then you may want to use preg_match :

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

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

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

Output:

29023487-1

Example - ideone

    
18.02.2017 / 01:49
1

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 .

    
18.02.2017 / 02:01