Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove everything but numbers and minus sign PHP preg_replace

I've currently got

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

For example the input is GB -3. My current line is giving me the value 3. I want to be able to keep the minus so that the value shows -3 instead of the current output of 3.

like image 319
Tim Nichols Avatar asked Aug 10 '12 02:08

Tim Nichols


People also ask

How remove non numeric characters PHP?

You can use preg_replace in this case; $res = preg_replace("/[^0-9]/", "", "Every 6 Months" );

What does preg_ replace() return?

The preg_replace() function returns a string or array of strings where all matches of a pattern or list of patterns found in the input are replaced with substrings. There are three different ways to use this function: 1. One pattern and a replacement string.

What is the use of preg_ replace in php?

PHP | preg_replace() Function The preg_replace() function is an inbuilt function in PHP which is used to perform a regular expression for search and replace the content.

How can I get only characters in a string in PHP?

$result = preg_replace("/[^a-zA-Z0-9]+/", "", $s);


1 Answers

try this :

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

breakdown of regex:

  • // on both sides are regex delimiter - everything that is inside is regex
  • [] means that this is character class. Rules change in character class
  • ^ inside character class stands for "not".
  • \d is short for [0-9], only difference is that it can be used both inside and outside of character class
  • - will match minus sign
  • + in the end is the quantifier, it means that this should match one or more characters
like image 114
Oussama Jilal Avatar answered Sep 28 '22 08:09

Oussama Jilal