tags:

views:

29

answers:

2

Hello,

I have two arrays one with OS's such as Ubuntu and Windows and another with system templates like Ubuntu 5.3 blah blah and Windows XP SP2 blah blah and I need to extract the OS from the system templates array, however it is not always at the start, sometimes it is in the middle or at the end. So how could I loop through one array and check to see if it is there in another array, if so tell me what the OS is.

Example.

OS List

$os = array("Ubuntu", "Debian", "Gentoo", "Windows", "Fedora", "CentOS", "CloudLinux", "Slackware");

Small section of the list of system templates (this will be in an array)

Ubuntu 8.04 x64 LAMP Installation
Ubuntu 8.04 x64 MySQL Installation
Ubuntu 8.04 x64 PHP Installation
x64 Installation Gentoo
Basic Installation Ubuntu 8.03

Which would result give me

Ubuntu
Ubuntu
Ubuntu
Gentoo
Ubuntu

Thanks

A: 

Call your first array (of arbitrary strings possibly containing os names) $foo and the search terms $os, then $result will be an array corresponding to $foo with the names from $os:

$result = array();
for($i = 0; $i < length($foo); $i++){
    // set the default result to be "no match"
    $result[$i] = "no match";

    foreach($os as $name){
        if(stristr($foo[$i], $name)){
            // found a match, replace default value with
            // the os' name and stop looking
            $result[$i] = $name;
            break;
        }
    }
}
Mark E
A: 

Make a regex out of the list of OS's to match against each template string, then map over each template string with that regex:

function find_os($template) {
  $os = array("Ubuntu", "Debian", "Gentoo", "Windows", "Fedora", "CentOS", "CloudLinux", "Slackware");
  preg_match('/(' . implode('|', $os) . ')/', $template, $matches);
  return $matches[1];
}

$results = array_map('find_os', $os_templates);

array_map() applies the find_os() function to each template string, giving you back an array of matched OS's.

yjerem