I
I
IvanMogilev2021-08-12 21:04:32
PHP
IvanMogilev, 2021-08-12 21:04:32

How to strip numbers with underscores?

Good afternoon, there are several types of file names, for example - 302_pp_kamenno_seriy_brown.jpeg, yasen_beliy_523_2.jpg, bej_yasen_beliy_601.jpeg

You need numbers and if there are further underscores, and then numbers again - then move them to the beginning of the line. Need help in compiling a regular expression, or maybe it can be done differently, at the moment I came to the code

<?php

if ($handle = opendir(dirname(__FILE__) . '/photo')) {
    while (false !== ($fileName = readdir($handle))) {
        
            preg_match('/(\\d+)_/', $fileName, $match);
            if(!empty($match)  )
            {
                foreach ($match as $item)
                {
                    if (stripos($item,"_"))
                    {
                        print_r($item);
                        echo "\n";
                    }
                }
            }
    }
    closedir($handle);
}
?>

but it cuts out only numbers with an underscore, if you do a regular expression like this, '/(\\d+)_(\\d+)/'it doesn't cut out just 601. Thanks in advance

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey delphinpro, 2021-08-12
@IvanMogilev

I don't like regular expressions =)
not the best solution, but it seems to work https://regex101.com/r/jG5UuA/1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question