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.
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.
The preg_match() function will tell you whether a string contains matches of a pattern.
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}+$/.
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.
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 );
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.[^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
).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With