[英]Search string for values in array
我有從MySQL獲取的地址,例如:
$address="This Street, Nice Area, That Country";
$address="This Street, Superb Area, Which Country";
$address="This Street, Fine Area, A Country";
現在我想做的就是找到AREA-就像$area=array("Nice", "Good")
。 因此,如果在$address
找到$area
定義的值,則應列出該值,否則將留空。
嘗試類似
$area=array(1=>"Nice", "Good");
$address = 'This Street, Nice Area, That Country';
preg_match(', (\w+) Area,', $address, $res);
$is_area = array_search( $res[1], $area, true) ;
if($is_area) echo $address;
說明
第一行將區域數組設置為以索引1而不是零開始(確保查找不返回零)
preg_match行從地址中提取區域
陣列搜索線在您的區域陣列中查找該區域
我認為您的要求可以解釋為:
“ 列出所有包含在$area
數組中找到的字符串實例的$ address字符串。 ”
在這種情況下:
// Set up.
$address = array(
"This Street, Nice Area, That Country",
"This Street, Superb Area, Which Country",
"This Street, Fine Area, A Country",
);
$area = array("Nice", "Good");
// The search.
$results = array();
foreach ($address as $haystack) {
foreach ($area as $needle) {
$regexPattern = "#{$needle}#";
if (preg_match($regexPattern, $haystack))
array_push($results, $haystack);
}
}
// The results.
foreach ($results as $result) {
echo "<p>{$result}</p>";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.