我有一个看起来像这样的数组:
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"
我怎么能用简单的方法做到?
答案 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)
_([^_]*)-
您可以改用它。这不允许其他_
。