Extract one or more qualifying substrings from each string in an array

Viewed 100

I am trying to extract qualifying substrings from an array of strings. Some strings in the array have just one qualifying substring, but others may have more. I need to build a flat array of all of these wanted values.

The following is my current Codeigniter method, but it doesn't handle cases when more than one qualifying substring exists.

public function generatenewname()
{
    $this->load->helper('directory');
    $map = directory_map('./assets/file_upload/md/temp/', FALSE, TRUE);
    for ($x = 0; $x < count($map); $x++) {
        $newest[$x] = explode(" ", $map[$x]);
        for ($y = 0; $y < count($newest[$x]); $y++) {
            if (strlen($newest[$x][$y]) >= 7) {
                $file[] = $newest[$x][$y];
            }
        }
    }
    for ($x = 0; $x < count($file); $x++) {
        echo $x . ' ' . $file[$x] . '<br>';
    }
}

Assume that my $map array contains this:

$map = [
    'BACK PACK BBP160800103  G086-1 8#.JPG',
    'BACKPACK BBP160500010 G114-3#1.JPG',
    'WSL160800024-WSL160800025 L83-5.JPG',
    'IA041017 L83-5.JPG'
];

Desired result:

[
    'BBP160800103',
    'BBP160500010',
    'WSL160800024',
    'WSL160800025',
    'IA041017'
]
4 Answers

More directly than exploding the strings and scavenging through the smitherings, call preg_match_all() on the strings to articulately pick out the qualifying substrings, then unpack those one-or-more substrings inside of an array_push() call.

Code: (Demo)

$result = [];
foreach ($map as $string) {
    array_push($result, ...preg_match_all('/\b(?:BBP|WSL|IA)\d{6,9}\b/', $string, $m) ? $m[0] : []);
}
var_export($result);
Related