Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP regular expression - filter number only

Tags:

regex

php

I know this might sound as really dummy question, but I'm trying to ensure that the provided string is of a number / decimal format to use it later on with PHP's number_format() function.

How would I do it - say someone is typing 15:00 into the text field - what regular expression and php function should I use to remove the colon from it and make it only return the valid characters.

preg_match() returns array - so I can't pass the result to number_format() unless I implode() it or something like this.

Your help would be very much appreciated.

like image 676
user398341 Avatar asked Mar 29 '11 14:03

user398341


People also ask

How do you use numbers in regular expressions?

To match any number from 0 to 9 we use \d in regex. It will match any single digit number from 0 to 9. \d means [0-9] or match any number from 0 to 9. Instead of writing 0123456789 the shorthand version is [0-9] where [] is used for character range.

What is the purpose of Preg_match () regular expression in PHP?

The preg_match() function will tell you whether a string contains matches of a pattern.

How can I set 10 digit mobile number in PHP?

Let's say that the genuine phone number is 10 digits long, ranging from 0 to 9. To perform the validation, you have to utilize this regular expression: /^[0-9]{10}+$/.

What is pattern matching in PHP?

preg_match() in PHP – this function is used to perform pattern matching in PHP on a string. It returns true if a match is found and false if a match is not found. preg_split() in PHP – this function is used to perform a pattern match on a string and then split the results into a numeric array.


2 Answers

Using is_numeric or intval is likely the best way to validate a number here, but to answer your question you could try using preg_replace instead. This example removes all non-numeric characters:

$output = preg_replace( '/[^0-9]/', '', $string ); 
like image 119
buley Avatar answered Sep 22 '22 19:09

buley


To remove anything that is not a number:

$output = preg_replace('/[^0-9]/', '', $input); 

Explanation:

  • [0-9] matches any number between 0 and 9 inclusively.
  • ^ negates a [] pattern.
  • So, [^0-9] matches anything that is not a number, and since we're using preg_replace, they will be replaced by nothing '' (second argument of preg_replace).
like image 35
netcoder Avatar answered Sep 20 '22 19:09

netcoder