phparraysregexfilter

How to filter an array of URLs that match a pattern


I've got an array with URLs in it like so:

$urls = array(
    "http://myurl.com/file/2222/file.rar",
    "http://myurl.com/file/2222/file.part1.rar",
    "http://myurl.com/file/2222/file.part2.rar",
    "http://myurl/file/2222/file.part3.rar",
    "http://myurl.com/file/2222/file.part4.rar"
);

I want to find any of the filenames to check if they are a part or a single file.

For example the result for the above should be:

$single = "http://myurl.com/file/2222/file.rar";
$splits = array("http://myurl.com/file/2222/file.part1.rar", "http://myurl.com/file/2222/file.part2.rar", "http://myurl.com/file/2222/file.part3.rar", "http://myurl.com/file/2222/file.part4.rar");

Solution

  • I like preg_grep():

    $parts = preg_grep('/\.part\d+\.rar/', $urls);
    $singles = array_diff($urls, $parts);
    

    Or to do the opposite for the singles:

    $singles = preg_grep('/\.part\d+\.rar/', $urls, PREG_GREP_INVERT);