我想创建一个PHP脚本,它接受由许多不同的单词或术语组成的PHP GET变量$_GET[q]
并检查它是否包含存储在数组中的任何"关键字"。这方面的一个例子是它可能看起来像"旧金山几点了"。我希望脚本以"时间"和"旧金山"为例。我玩过使用
if(stripos($_GET[q],'keyword1','keyword2'))
但运气并不好。
有谁知道我该怎么做?
我希望每个人都能理解我想描述的内容。
您可以创建一个关键字数组,然后循环播放,直到找到匹配项。
$array = array('keyword1', 'keyword2');
$found = false;
foreach($array as $x){
if(stripos($_GET['q'], $x) !== false){
$found = true;
break;
}
}
if($found){
}
更新:如果您想匹配所有关键字,您可以改为这样做:
$array = array('keyword1', 'keyword2');
$found = true;
foreach($array as $x){
$found &= stripos($_GET['q'], $x) !== false;
}
if($found){
}
演示:http://codepad.org/LaEX6m67
更新 2:因为我疯了,喜欢单行代码,你可以在 PHP 5.3+ 中做到这一点:
$array = array('keyword1', 'keyword2');
$val = $_GET['q'];
$found = array_reduce($array, function($x, $v) use($val){
return $x && stripos($val, $v) !== false;
}, true);
if($found){
}
演示:http://codepad.viper-7.com/Y48sHR
foreach($arr as $value){
if(stripos($_GET[q],$value){
do stuff
}
}
使用in_array函数:
// assuming $arr is your array of keywords
if (in_array($_GET['q'], $arr))
echo "found a match'n";
编辑:根据您的评论,这里是您可以使用的代码,无需任何循环即可工作:
$arr = array('keyword1', 'keyword2', 'keyword3');
$brr = array_map(create_function('$m', 'return "/'b" . $m . "'b/";'), $arr);
if ($_GET['q'] !== preg_replace($brr, '', $_GET['q']))
echo "found a match'n";
else
echo "didn't find a match'n";