Jaroslav Klimčík
Jaroslav Klimčík

Reputation: 4838

Parse after last character and before another character

I have an array which looks this:

array(7) [
  0 => "account_bad_rooms_view-1" (24)
  1 => "account_view-2" (14)
  2 => "admin_collector_view-5" (22)
  3 => "admin_collector_edit-5" (22)
  4 => "machine_service_item_edit-57" (28)
  5 => "money_view-58" (13)
  6 => "mu_edit-61" (10)
]

And I need to get substring which will be contain only "edit" or "view" so I need parse this string after last underscore and before dash. So far I have this:

foreach ($permissionsArray as $selectId => $permissions) {

    preg_match('~_(.*?)-~', $permissions, $output);
    dump($output[1]);

}

which work for strings where is only one underscore, so the result is:

"bad_rooms_view"
"view"
"collector_view"
"collector_edit"
"service_item_edit"
"view"
"edit"

how can I do it with easy way?

Upvotes: 1

Views: 45

Answers (2)

anubhava
anubhava

Reputation: 786091

You can get your output using preg_filter function without using any loop:

$array=array("account_bad_rooms_view-1", "account_view-2", "admin_collector_view-5",
  "admin_collector_edit-5", "machine_service_item_edit-57", "money_view-58", "mu_edit-61");

$matches = preg_filter('/^.+?_([^-_]+)-.*$/', '$1', $array);

print_r($matches);

Output:

Array
(
    [0] => view
    [1] => view
    [2] => view
    [3] => edit
    [4] => edit
    [5] => view
    [6] => edit
)

Upvotes: 2

vks
vks

Reputation: 67988

_([^_]*)-

You can use this instead.This will not allow another _.

Upvotes: 1

Related Questions