1

I have a select box:

<select name="count">
    <option value="0">Select count</option>
    <option value="1">1</option>
    <option value="2">2</option>
    ..
    <option value="5">5</option>
    <option value="5+">5+</option>
</select>

So I want to check if the value is an integer or 5+.

I tried:

$pattern = '/^[0-9]*?[0-9+]$/';
$count = '1';

if(preg_match($pattern, $count)){
    echo 'Valid';
}else{
    echo 'Invalid';
}

That returns Valid.

$count = '10+';

That also returns Valid.

But not sure if that's working well or not.

Is it checking integer or integer+?

I want to check for an integer or 5+ only.

3 Answers3

0

You need to use

$pattern = '/^\d+\+?$/';
zen
  • 900
  • 6
  • 18
  • The pattern is checking for integers or integer+, But I want to specify the part of `integer+` to `5+` only or an integer like `1 2 3 ..` –  Aug 15 '18 at 14:15
  • 1
    Then use `'/^\d+|5\+$/` – zen Aug 15 '18 at 15:12
0

You can use ^\d+(\+?)$ to allow for + after any digit.

$pattern = '/^\d+(\+?)$/';
preg_match($pattern, '1'); // Match
preg_match($pattern, '5+'); // Match
preg_match($pattern, '10+'); // Match

If you only want to allow for 5+ specifically then ^(\d+|5\+)$ should do the job.

$pattern = '/^(\d+|5\+)$/';
preg_match($pattern, '1'); // Match
preg_match($pattern, '5+'); // Match
preg_match($pattern, '10+'); // No match

You can see both of the above working in a sandbox.

Jim Wright
  • 5,256
  • 1
  • 9
  • 30
0

You may use

'~^(?:\d+|5\+)$~D'

See the regex demo

Details

  • ^ - start of string
  • (?: - a non-capturing group that matches either of the two patterns:
    • \d+ - one or more digits
    • | - or
    • 5\+ - 5+ substring
  • ) - end of the group
  • $ - the very end of the string (since PCRE_DOLLAR_ENDONLY D modifier does not allow $ to match before the final newline char in the string).
Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397