在最后一个字符之后和另一个字符之前解析

时间:2015-08-12 06:47:05

标签: php regex parsing substring

我有一个看起来像这样的数组:

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

我需要获得仅包含"edit""view"的子字符串,因此我需要在最后一个下划线之后和破折号之前解析此字符串。到目前为止,我有这个:

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

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

}

适用于只有一个下划线的字符串,因此结果为:

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

我怎么能用简单的方法做到?

2 个答案:

答案 0 :(得分:2)

您可以使用preg_filter函数获取输出,而无需使用任何循环:

$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);

<强>输出:

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

答案 1 :(得分:1)

_([^_]*)-

您可以改用它。这不允许其他_