[英]search for string from array in another array
我有兩個陣列,一個帶有操作系統(如Ubuntu和Windows),另一個帶有系統模板(如Ubuntu 5.3等)和Windows XP SP2等,我需要從系統模板數組中提取OS,但是這並不總是一開始的,有時它在中間或結尾。 因此,我該如何遍歷一個陣列並檢查它是否在另一個陣列中,如果可以,請告訴我什么操作系統。
例。
操作系統列表
$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
謝謝
調用您的第一個數組(可能包含操作系統名稱的任意字符串) $foo
和搜索項$os
,然后$result
將是名稱為$os
與$foo
對應的數組:
$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;
}
}
}
從操作系統列表中創建一個正則表達式以與每個模板字符串匹配,然后使用該正則表達式映射每個模板字符串:
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()
函數應用於每個模板字符串,從而為您提供匹配操作系統的數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.