John
John

Reputation: 107

Conditional regex php

I'm facing some problem with php regex but after many researches (conditional regex, subpattern regex), I still can't solve it.

I have a folder that contains many images and based on variable value I have to go to that folder and select all images that match the value. e.g: In my folder I have 3 images:

p102.jpg ; p1020.jpg ; p102_1.jpg;

I only want the regex to select :

p102.jpg ; p102_1.jpg

but with the regex below It selects all 3 images.

$image_to_find = 102;
$path = "[^\d]*.*/"
$test = "/^[a-zA-Z]?$image_to_find".$path;
foreach(glob($file_directory) as $file){
 if(preg_match($test, $file)){
   match[]= $file;
 }
}

I also try:

$path = "(?:\_[0-9]?).*/"; (it selects only p102_1.jpg)

Can you help me to figure it out. thanks (sorry for the english)

Upvotes: 2

Views: 75

Answers (4)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89547

You can avoid the foreach loop if you use the glob pattern:

$num = 102;

$result = glob($path . '[a-zA-Z]' . $num . '[._]*');

Note: if you need to allow several different formats, you can use array_merge and several glob patterns: array_merge(glob(...), glob(...));

If you want the first letter optional:

$result = array_merge(
    glob($path . $num . '[._]*jpg'),
    glob($path . '[a-zA-Z]' . $num . '[._]*jpg')
);

or better, use the brace option:

$result = glob($path . '{[a-zA-Z],}' . $num . '[._]*jpg', GLOB_BRACE);

That stays a better alternative than the combo "foreach/preg_match" (or preg_grep) if filenames are not too complicated.

With preg_grep:

$pattern = '~(?:^|/)[a-z]?' . $num . '(?:_\d+)?\.jpg$~i';
$result = preg_grep($pattern, glob($path . '*' . $num . '*.jpg'));

Upvotes: 2

Allan Andrade
Allan Andrade

Reputation: 710

Tested and working:

<?php
$image_to_find = 102;
$pattern = '[a-zA-Z]' . $image_to_find . '[._]*';
$path = '/your_folder/your_subfolder/';
$file_directory = glob($path . $pattern );
echo '<pre>';
var_dump($file_directory);
echo '</pre>';
exit();

I hope this helps!

Upvotes: -1

Ido
Ido

Reputation: 2054

Not tested, should work.

$find = 102;
$pattern = "/p". $find ."(?:_\d+)?\.jpg/";
$list = array();

foreach (glob($file_directory) as $file)
{
    if (preg_match($pattern, $file))
    {
        $list[] = $file;
    }
}

regex: http://regexr.com/3bp29

Upvotes: 0

mayo
mayo

Reputation: 4075

Try this:

/p102[_\.]\d*\.?jpg/g

https://regex101.com/r/hM4oE0/1

Where p102 should be your 'image_to_find' var.

Upvotes: 1

Related Questions