Delete everything except numbers and minus sign PHP preg_replace

I have currently received

preg_replace('/[^0-9]/s', '', $myvariable); 

For example, entering GB -3. My current line gives me a value of 3. I want to be able to save the minus so that the value shows -3 instead of the current output of 3.

+6
source share
1 answer

try the following:

 preg_replace('/[^\d-]+/', '', $myvariable); 

regex breakdown:

  • // on both sides is a regular expression separator - everything inside is a regular expression
  • [] means that it is a character class. Change rules in a character class
  • ^ Inner character class means not.
  • \d abbreviated for [0-9], the only difference is that it can be used both inside and outside the character class
  • - will match the minus sign
  • + at the end - a quantifier, which means that it must match one or more characters.
+9
source

Source: https://habr.com/ru/post/922534/


All Articles