Search code examples
phparraysloopssubstringtext-extraction

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


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'
]

Solution

  • Pass your final array to this function to achieve your result.

    arraymakking($file);//your array
    
    function arraymakking($arr){
        foreach($arr as $key=>$val){
            if(strpos($val,'-') !== false){
                $res=explode('-',$val);
                unset($arr[$key]);
            }
        }
        $result=array_merge($arr,$res);
        return $result;
    }