Include into php array only the values surrounded by same specific symbols

Viewed 46

I have a folder with filenames like -abc-de.php, -bcd-ef.php, -cd-efg.php and say index.php.

I need to feel my array only with file names which contain symbols surrounded by -, may be even limit the number of those symbols strictly to 3, just in case. And truncate their names to those 3 symbols surrounded by -.

In other words I need my array to look like Array ( [0] => abc [1] => bcd ).

My partly working solution is the following:

$array = scandir('folder');
foreach($array as $key => $val){
    $array[$key] = substr($val,1,3);
}

It does the job but also includes cd- and nde which I definitely do not need in my array.

Please help me to make my array exactly as I want it to be.

------- UPDATE -------

With great help of @AbraCadaver I've finally made the following code that seems to be what I need:

$array = scandir('folder');
$array = preg_grep('/-([a-z]{3})-/', $array);
foreach($array as $key => $val){
    if(preg_match('/-([a-z]{3})-/', $val, $match)) {
        $array[$key] = $match[1];
    }
}

I could understand @AbraCadaver wrongly and made something different from what was originally suggested. But it does exactly what I needed.

One more question though:

$array = scandir('folder');
foreach($array as $key => $val){
    if(preg_grep('/-([a-z]{3})-/', $val, $match)) {
        $array[$key] = $match[1];
    }
}

Why the above construction doesn't work?

2 Answers

This will match - and 3 letters and then - and store the letters in $match[1]. Do this in the loop:

if(preg_match('/-([a-z]{3})-/', $val, $match)) {
    $array[$key] = $match[1];
}

To get uppercase and lowercase use the i modifier:

/-([a-z]{3})-/i

To force the match to start at the beginning of the string use the ^ anchor:

/^-([a-z]{3})-/i

Use any combination. You can change a-z to a-z0-9 for letters and numbers for example.

Another option would be:

$files = glob('folder/-???-*');

Or some variation, and then your substr will get the characters you want.

You can filter out any value if a string has a - in it

$newArray = array_filter($array, fn($string) => strpos($string, '-' === false));
Related