从另一个阵列中的数组搜索字符串
问题描述:
我有两个数组,一个是OS,比如Ubuntu和Windows,另一个是系统模板,比如Ubuntu 5.3等等等等,而Windows XP SP2等等等等,我需要从系统模板中提取操作系统数组,但它并不总是在开始,有时它在中间或结束。那么我怎么能通过一个数组循环,并检查它是否在另一个数组中,如果是的话告诉我操作系统是什么。从另一个阵列中的数组搜索字符串
例子。
操作系统列表
$os = array("Ubuntu", "Debian", "Gentoo", "Windows", "Fedora", "CentOS", "CloudLinux", "Slackware");
的系统模板列表中的小部分(这将是一个数组)
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
会导致这给我
Ubuntu
Ubuntu
Ubuntu
Gentoo
Ubuntu
感谢
答
做一个正则表达式淘汰之列操作系统的匹配对每个模板的字符串,然后在每个模板字符串映射与正则表达式:
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()
应用find_os()
功能,每个模板字符串,以便让您匹配OS的数组”秒。
答
打电话给你的第一阵列$foo
和搜索字词$os
(任意的字符串可能包含操作系统的名称),然后$result
将相应的阵列$foo
与名称从$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;
}
}
}