Jump to content

Using preg match to find specific cluster of files


Go to solution Solved by Barand,

Recommended Posts

Hi guysm

I have a folder containing these files:

alg001.php
alg002.php
alg003.php
alg004.php
alg005.php
algComp.php
ranFrac.php
ranalg.php
randec.php
randint.php

I would only like to store the names of files alg001.php, alg002.php, alg003.php, alg004.php, alg005.php into an array. How do i achieve this with preg match?

Easier with str_starts_with()

$files = [  'alg001.php',
            'alg002.php',
            'alg003.php',
            'alg004.php',
            'alg005.php',
            'algComp.php',
            'ranFrac.php',
            'ranalg.php',
            'randec.php',
            'randint.php'
          ];
$required = array_filter($files, fn($v)=>str_starts_with($v, 'alg00'));
echo '<pre>' . print_r($required, 1) . '</pre>';

Gives

Array
(
    [0] => alg001.php
    [1] => alg002.php
    [2] => alg003.php
    [3] => alg004.php
    [4] => alg005.php
)

 

32 minutes ago, Barand said:

Easier with str_starts_with()

$files = [  'alg001.php',
            'alg002.php',
            'alg003.php',
            'alg004.php',
            'alg005.php',
            'algComp.php',
            'ranFrac.php',
            'ranalg.php',
            'randec.php',
            'randint.php'
          ];
$required = array_filter($files, fn($v)=>str_starts_with($v, 'alg00'));
echo '<pre>' . print_r($required, 1) . '</pre>';

Gives

Array
(
    [0] => alg001.php
    [1] => alg002.php
    [2] => alg003.php
    [3] => alg004.php
    [4] => alg005.php
)

 

I tried as suggested:

$arrFiles = array();
$dirPath = "./";
$files = scandir($dirPath);
$required = array_filter($files, fn($v)=>str_starts_with($v, 'alg00'));
echo '<pre>' . print_r($required, 1) . '</pre>';

The error:

Fatal error: Uncaught Error: Call to undefined function str_starts_with() ...php:29 Stack trace: #0 [internal function]: {closure}('.') #1 /...php(29): array_filter(Array, Object(Closure)) #2 {main} thrown in ...php on line 29

 

Posted (edited)
14 minutes ago, Barand said:

You must be using an outdated version of php. Str_starts_with() requires version 8.

Use this instead

$required = array_filter($files, fn($v)=>substr($v, 0, 5) == 'alg00');

 

What does the values in 0,5 in substr($v, 0, 5) refers to?

Edited by shamuraq

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.