0

I have an array that looks something like this:

$array =  array( [0] => FILE-F01-E1-S01.pdf 
                 [1] => FILE-F01-E1-S02.pdf 
                 [2] => FILE-F01-E1-S03.pdf 
                 [3] => FILE-F01-E1-S04.pdf 
                 [4] => FILE-F01-E1-S05.pdf 
                 [5] => FILE-F02-E1-S01.pdf 
                 [6] => FILE-F02-E1-S02.pdf 
                 [7] => FILE-F02-E1-S03.pdf );

Basically, I need to look at the first file and then get all the other files that have the same beginning ('FILE-F01-E1', for example) and put them into an array. I don't need to do anything with the other ones at this point.

I've been trying to use a foreach loop finding the previous value to do this, but am not having any luck.

Like this:

$previousFile = null;

foreach($array as $file)
{

    if(substr_replace($previousFile, "", -8) == substr_replace($file, "", -8)) 
    {
        $secondArray[] = $file;
     }

    $previousFile = $file;
}

So then $secondArray would look like this:

    Array ( [0] => FILE-F01-E1-S01.pdf [1] => FILE-F01-E1-S02.pdf 
            [2] => FILE-F01-E1-S03.pdf [3] => FILE-F01-E1-S04.pdf 
            [4] => FILE-F01-E1-S05.pdf)

As my result.

Thank you!

5
  • Sample code always helps to see where you are so far. Would it be possible to use a simple foreach() and if(), with a regular expression condition? Commented Sep 27, 2018 at 18:40
  • First you need to define your pattern. Is it always going to be FILE-F[NUMBER]-*.pdf ? What is your use case for the array? Do you just want to get let's say F01 files array or you want to parse them all at once into their separate arrays? Please provide us with more context. Commented Sep 27, 2018 at 18:43
  • @falnyr The files will vary in how they are named. I can't do a strpos() on them because it will differ. I can, however always remove the last 8 characters to match them. And, yes, I do just want an array of F01 files. That's all I need to do at this point. I hope that clears things up a bit. Commented Sep 27, 2018 at 18:51
  • @matty_eng Are you sure about the last 8 characters? What you are showing here seems to be a list of episodes for a TV show. What if the name would be E01-S1 can that happen? Commented Sep 27, 2018 at 18:55
  • Why are you reassigning $previousFile every time through the loop? You said you just want to use the first file to get the pattern. Commented Sep 27, 2018 at 19:09

4 Answers 4

1

You can use array_filter combined with strpos:

$result = array_filter($array, function($filename) { 
  return strpos($filename, 'FILE-F01-E1') === 0; 
});
Sign up to request clarification or add additional context in comments.

Comments

0

Are you sure this will be the naming format? That is crucial information to have to construct a regexp or something to check for being a substring of the following strings.

If we can assume this and that the "base" name is always at index 0 then you could do something like.

<?php
    $myArr =  [ 
                'FILE-F01-E1-S01.pdf', 
                'FILE-F01-E1-S02.pdf', 
                'FILE-F01-E1-S03.pdf', 
                'FILE-F01-E1-S04.pdf', 
                'FILE-F01-E1-S05.pdf', 
                'FILE-F02-E1-S01.pdf', 
                'FILE-F02-E1-S02.pdf', 
                'FILE-F02-E1-S03.pdf'
              ];

    $baseName        = '';
    $allSimilarNames = [];

    foreach($myArr as $index => &$name) {
      if($index == 0) {
          $baseName = substr($name, 0, strrpos($name, '-'));
          $allSimilarNames[] = $name;
      }
      else {
          if(strpos($name, $baseName) === 0) {
              $allSimilarNames[] = $name;
          }
      }
    }

    var_dump($allSimilarNames);

This will

  • Check at index one to get the base name to compare against
  • Loop all items in the array and match all items, no matter where in the array they are, that are similar according to your naming convention

So if you next time have an array that is

$myArr =  [ 
                    'FILE-F02-E1-S01.pdf',
                    'FILE-F01-E1-S01.pdf', 
                    'FILE-F01-E1-S02.pdf', 
                    'FILE-F01-E1-S03.pdf', 
                    'FILE-F01-E1-S04.pdf', 
                    'FILE-F01-E1-S05.pdf', 
                    'FILE-F02-E1-S02.pdf', 
                    'FILE-F02-E1-S03.pdf'
                  ]; 

this will return all the items that match FILE-F02-E1*.

You could also make a small function of it for easier use and not have to rely on the element at index 0 having to be the "base" name.

<?php
function findMatches($baseName, &$names) {
    $matches = [];
    $baseName = substr($baseName, 0, strrpos($baseName, '-'));
    foreach($names as &$name) {
        if(strpos($name, $baseName) === 0) {
          $matches[] = $name;
        }
    }

    return $matches;
}

$myArr =  [ 
            'FILE-F01-E1-S01.pdf', 
            'FILE-F01-E1-S02.pdf', 
            'FILE-F01-E1-S03.pdf', 
            'FILE-F01-E1-S04.pdf', 
            'FILE-F01-E1-S05.pdf', 
            'FILE-F02-E1-S01.pdf', 
            'FILE-F02-E1-S02.pdf', 
            'FILE-F02-E1-S03.pdf'
          ];

$allSimilarNames = findMatches('FILE-F01-E1-S01.pdf', $myArr);

var_dump($allSimilarNames);

3 Comments

Instead of testing $index == 0 every time through the loop, why not just initialize $baseName using $myArr[0]?
Thank you! I think this is exactly what I needed.
@Barmar: I initially had the check since I was unsure that the item at index 0 should be part of the result. So I first never added that to the array. Then when I changed it I didn't refactor the code flow. That is why I added the example with making it a function instead since that is a "better" solution. The initial one with the reach was just a quick and dirty solution.
0

Run a simple foreach with strpos() which looks for an occurrence of a string within a string.

 $results = array();

 foreach($array as $item){
      if (strpos($item, 'FILE-F01-E1') === 0) {
           array_push($results, $item);
      }
 }

7 Comments

I believe your strpos test is wrong. First position will return 0 which doesn't evaluate to true. Any other position will evaluate to true (after your edit, with === the condition will never be met now :) )
Thanks. I believe that I have fixed it!
Almost: I believe you meant === 0. You want to add the items which do have that string at their first position.
Ah yes. To be honest, this is not the best use of strpos(). I appreciate the corrections! I actually was unaware of the array_filter() function! Very handy.
@inquam Thanks for the feedback. However I am only interested in the condition being met if the position of the desired string is at place 0. I don't want to condition to be met if it is indeed false.
|
0

You could get the first item from the array and use explode and implode to get the part from the filename without the last hyphen and the content after that.

Then use array_filter and use substr using 0 as the start position and the length of the $fileBeginning as the length to check if the string starts with FILE-F01-E1:

$array = [
    'FILE-F01-E1-S01.pdf',
    'FILE-F01-E1-S02.pdf',
    'FILE-F01-E1-S03.pdf',
    'FILE-F01-E1-S04.pdf',
    'FILE-F01-E1-S05.pdf',
    'FILE-F02-E1-S01.pdf',
    'FILE-F02-E1-S02.pdf',
    'FILE-F02-E1-S03.pdf',
    "TESTFILE-F01-E1-S03.pdf"
];
$parts = explode('-', $array[0]);
array_pop($parts);
$fileBeginning =  implode('-', $parts);
$secondArray = array_filter($array, function ($x) use ($fileBeginning) {
    return substr($x, 0, strlen($fileBeginning)) === $fileBeginning;
});
print_r($secondArray);

Result

Array
(
    [0] => FILE-F01-E1-S01.pdf
    [1] => FILE-F01-E1-S02.pdf
    [2] => FILE-F01-E1-S03.pdf
    [3] => FILE-F01-E1-S04.pdf
    [4] => FILE-F01-E1-S05.pdf
)

Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.