'PHP using str_starts_with for array to exclude same as with wildcard

This is my ignore list which i have some item that i don't into that

$ignoreRoutes = [
    'administrator',
    'attachImage',
    'login',
    'logout',
    'loginToPanel',
    'attachImage',
    'settingsList',
    'settingsCreate',
    'settingsStore',
    'settingsEdit',
    'settingsUpdate',
    'settingsDestroy',
    'usersPermission',
    'posts'
];

here i have 'usersPermission.index','usersPermission.create','usersPermission.update' and more item same as this list which i don't have in the ignore list and i want to check them in array like with wildcard, for example:

$collection = Route::getRoutes()->getRoutesByName();

foreach (array_keys($collection) as $collect) {
    $array = array_filter($ignoreRoutes, function($key) use ($collect) {
        return str_starts_with($key, $collect);
    }, ARRAY_FILTER_USE_BOTH);

    if (count($array)>0 && is_array($array) && $array) {
        // item doesn't exists in ignore list and should be print
    }
}

it means i want to check 'usersPermission.index' with each item in ignore list when started with for example usersPermission. i tested above code and don't work correctly, could you please help me to implementing this action? thanks in adavance



Solution 1:[1]

You can use strpos() and foreach(). Basically like this:

$ignoreRoutes = [
    'administrator',
    'attachImage',
    'login',
    'logout',
    'loginToPanel',
    'attachImage',
    'settingsList',
    'settingsCreate',
    'settingsStore',
    'settingsEdit',
    'settingsUpdate',
    'settingsDestroy',
    'usersPermission',
    'posts'
];

$tests = ['usersPermission.index','usersPermission.create','xx.create'];

foreach($tests as $test){

  $ignore = false;
  foreach($ignoreRoutes as $ignoreRoute){
    if(strpos($test,$ignoreRoute) === 0) {
      $ignore = true;
      break;
    }
  }
  if($ignore) echo 'ignore '.$test."<br>\n";
  else echo 'not ignore '.$test."<br>\n";

}

Output:

ignore usersPermission.index
ignore usersPermission.create
not ignore xx.create

I didn't use str_starts_with() because it's only available from PHP8 and I can't test it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jspit