1

I have this regex :

if(preg_match("@^\d{4}$@", basename($entry, ".php"))) { --do something here-- } 

that condition works only for 4 digits number. but I need to validate 4 digits and also 5 digits. how to make it work to validate 5 digits number too? thanks!

1

4 Answers 4

6

the braces can take a low and high end of a range so {4,5} should work.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 for the regular expression explanation. I encourage you to also provide a code sample.
Here's something you can run on the command line: php -r '$pattern = "/^\d{4,5}/"; preg_match($pattern, "12345678", $a); print_r($a);'
3

As an alternative to Regular Expressions, consider simpler functions like ctype_digit() and strlen().

$filename = basename($entry, ".php"); $length = strlen($filename); if (($length >= 4 && $length <= 5) && ctype_digit($filename)) { // your code } 

Comments

2
if(preg_match("@^\d{4,5}$@", basename($entry, ".php"))) { --do something here-- } 

Comments

2

instead of

 if(preg_match("@^\d{4}$@", basename($entry, ".php"))) { 

use

if(preg_match("@^\d{4,5}$@", basename($entry, ".php"))) { 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.