Php 在数组中搜索值的字符串
我从MySQL获取了如下地址:Php 在数组中搜索值的字符串,php,Php,我从MySQL获取了如下地址: $address="This Street, Nice Area, That Country"; $address="This Street, Superb Area, Which Country"; $address="This Street, Fine Area, A Country"; 现在我要做的是查找区域,就像$AREA=array(“Nice”,“Good”)。因此,如果在$area中找到了$address中定义的值,则该值应列出,否则保留为空。请尝
$address="This Street, Nice Area, That Country";
$address="This Street, Superb Area, Which Country";
$address="This Street, Fine Area, A Country";
现在我要做的是查找区域,就像$AREA=array(“Nice”,“Good”)
。因此,如果在$area
中找到了$address
中定义的值,则该值应列出,否则保留为空。请尝试类似的操作
$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_匹配线从地址中提取区域
数组搜索行在您的区域数组中查找区域我认为您的问题可以解释为:
“列出所有包含$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>";
}
//设置。
$address=数组(
“这条街,好地方,那个国家”,
“这条街,好地方,哪个国家”,
“这条街,好地方,一个国家”,
);
$area=数组(“好”、“好”);
//搜索。
$results=array();
foreach($haystack地址){
foreach($针头面积){
$regexpatern=“#{$needle}#”;
if(预匹配($regexpatern,$haystack))
数组推送($results,$haystack);
}
}
//结果。
foreach($results作为$result){
回声“{$result}”;
}
(确保查找结果不返回零)–您可以根据!==false
在您的if条件下。感谢您的快速帮助-但我的问题有一个小错误。在地址中,我们可能没有任何相同的值-它可以像时代广场、华尔街、中央公园等。对不起,我犯了一个愚蠢的错误。