Jump to content

regular expression for this pattern [a-z]-[a-z]


kevin7

Recommended Posts

I want to list all my files in a directory that has this pattern:

 

profile-create, profile-post, navigation-list, or access-list-create

 

all of them will have a hyphen in between two words

 

this is the one im developing, but it isnt working.

 

$files = scandir($basePath);
foreach($files as $key => $value){

if (preg_match("/^[a-z]*[\-][a-z]*$/", $value)) echo $value . '<br/>';

}

 

can anyone provide me a correct expression?

 

thanks.

You are using the star quantifier (so it could be [a-z], zero or more times... but you require two words, so you can change [a-z]* to [a-z]+ (one or more times), otherwise your pattern could simply match a single hyphen and that's it. Also, if the words have some upper case letters, your pattern won't match that, as it is looking for all lower case. You can simply add the i modifier after the closing / delimiter.

 

Also note that you don't need the dash in a character class (let alone escape it), as you are only checking for a single character... you can simply use -

 

Example:

$value = 'Blah-blah';
echo (preg_match('/^[a-z]+-[a-z]+$/i', $value))? $value . '<br/>' : 'error';

EDIT - Granted, this means it can match something like 'a-b'... so if there is a minimum number of characters in each word that you want, you can use intervals instead of the + quantifier (like if you use [a-z]{2,} this means 2 or more letters.. using something like [a-z]{2,20} creates a range between 2 and 20 letters.. that kind of thing).

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.