2

This should be a nice easy one for a regex expert.

I have a group name <APP>_<Resource>_<Action> the action segment contains a combination or CRUD. There are 13 possible combinations that these can appear in.

CRUD, CRU, CRD, CUD, RUD, CR, CU, CD, RU, RD, UD, C, R, U, D

I just want a regex to match on of those patterns within the action segment of the group name. The application and resources can change to various different strings.

Example Group Names

PM_folder1_cru, PM_folder2_ud, PM_folder3_cr, PM_folder4_cu, PM_personalFolder_crud

Thanks in advance

EDIT

This is currently done using:

$allowedActions = ['CRUD', 'CRU', 'CRD', 'CUD', 'RUD', 'CR', 'CU', 'CD', 'RU', 'RD', 'UD', 'C', 'R', 'U', 'D'];

if (in_array(strtoupper($action), $allowedActions)) {
1
  • CRD ah yeah, its still early i will just edit the post. and no it doesn't need to match an empty string. Commented Jun 13, 2013 at 8:02

3 Answers 3

2

I think something like this would work:

^C?R?U?D?$

To avoid matching empty strings, you can use a lookahead assertion:

^(?!$)C?R?U?D?$
Sign up to request clarification or add additional context in comments.

Comments

1

How about:

/^.*_(?=[CRUD]{1,4})C?R?U?D?$/i

usage:

$arr = array(
'PM_folder1_cru',
'PM_folder2_ud',
'PM_folder3_cr',
'PM_folder4_cu',
'PM_personalFolder_crud',
);

foreach ($arr as $str) {
    if (preg_match('/^.*_(?=[CRUD]{1,4})C?R?U?D?$/i', $str)) 
        echo "OK : $str\n";
    else
        echo "KO : $arr\n";
}

output:

OK : PM_folder1_cru
OK : PM_folder2_ud
OK : PM_folder3_cr
OK : PM_folder4_cu
OK : PM_personalFolder_crud

Comments

0

Note: This answer is assuming that APP contains only letters and Resource contains only letters and numbers.

You could do a more general matching by using a character class:
(?i)[a-z]+_[a-z0-9]+_[crud]{1,4}. Note that this will also match DRUC, DDDD, RRC for example.

If you don't want that, then you could use something more specific:
(?i)[a-z]+_[a-z0-9]+_(?:c?r?ud?|cr?d?|r?d|r)

What does this mean ?

  • (?i) : set the i modifier to match case insensitive
  • [a-z]+ : match letters one or more times
  • _ : match one underscore
  • [a-z0-9]+ : match letters and numbers one or more times
  • _ : match one underscore
  • (?:c?r?ud?|cr?d?|r?d|r) : match crud, cru, rud, c, r, d etc...

PHP code:
If you want to get the action in a separate (sub)array, you'll may add a named group and remove ?::

$string = 'PM_folder1_cru,
PM_folder2_ud,
PM_folder3_cr,
PM_folder4_cu,
PM_personalFolder_crud';
preg_match_all('#(?i)[a-z]+_[a-z0-9]+_(?P<action>c?r?ud?|cr?d?|r?d|r)#', $string, $m);
print_r($m['action']); // Get actions
print_r($m); // everything ?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.