user3065879
user3065879

Reputation: 29

preg_replace() optional pattern matching

I want to do some pattern matching on PHP using preg_match(). I want my users to enter an amount from their mobile device. so if they wanna enter 50.50, they could enter 50*50 (the asterisk here is the actual asterisk button on the phone). so i want to check the input for some validations. mainly 1. all the inputs have to be digits (excluding the asterisk) 2. the number of decimal points after the asterisk should be two. 3. the decimal digits are optional. that means a user can enter 50 or 50.50 both should be valid.

so far what i have is this. if( preg_match( "_\d{1,6}(\*\d{2})_" , $input) {//do something}. this code works partially, the problem is i cant make the sub-pattern search optional. i looked into the manual but couldn't find anything. i need help thank you

Upvotes: 1

Views: 184

Answers (2)

Pedro Lobito
Pedro Lobito

Reputation: 98991

$array = array("50.50", "50", "50*50", "4");

foreach($array as $number)
{
if (preg_match('/^[\d]{2}(\.|\*)?([\d]{2})?/sim', $number)) {
    echo $number ." VALID ";
} else {
    echo $number ." INVALID ";
    //Do something with the invalid number
}
}

OUTPUTS: 50.50 VALID 50 VALID 50*50 VALID 4 INVALID

DEMO

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324750

Add ? after the ) to make it optional. ? used as a quantifier means "zero or one" - ie. optional.

As a side-note, I'm not aware of any mobile devices that have a browser but don't let you type a . easily...

Upvotes: 1

Related Questions