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.

Link to comment
Share on other sites

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).

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.