if (strpos($text,'City') !== false)
...
在“IF”行中,我想检查几个参数。例如“城市,天气等”我该怎么做?
编辑:感谢您的所有答案
答案 0 :(得分:4)
if(strpos($text,'City') !== false && strpos($text,'Weather') !== false && ...)
琐碎,真的。
答案 1 :(得分:2)
您可以使用in_array()函数以另一种方式执行此操作。
$array = array('City','Weather','anything');
if (in_array($text, $array)) {
echo "Yes";
}
答案 2 :(得分:1)
Kolinks answer完全正确且非常简单。如果您更喜欢使用数组,那么您可以这样做:
您的典型OR
或||
替换:
<?php
$text = "I live in a City with some very bad Weather etc.";
$searchWords = array("City", "Weather", "etc");
$found = false;
foreach ($searchWords as $searchWord) {
if (strpos($text, $searchWord) !== false) {
$found = true;
break;
}
}
if ($found) {
//Do something
} else {
//Didn't find anything
}
?>
您的典型AND
或&&
替换:
<?php
$text = "I live in a City with some very bad Weather etc.";
$searchWords = array("City", "Weather", "etc");
$found = true; //start at true instead of false
foreach ($searchWords as $searchWord) {
if (strpos($text, $searchWord) === false) { //=== instead of !==
$found = false;
break;
}
}
if ($found) {
//Do something
} else {
//Didn't find anything
}
?>
答案 3 :(得分:1)
$text = "I live in a City with some very bad Weather etc.";
$searchWords = array("City", "Weather", "etc");
$finds = array();
foreach ($searchWords as $searchWord) {
if (strpos($text, $searchWord) !== false) {
!isset($finds[$searchWord]) and ($finds[$searchWord] = 0);
$finds[$searchWord]++; // increment finds
}
}
if (count($finds) === count($searchWords)) {
// found ALL words
}elseif (!empty($finds)) {
// found SOME words
} else {
// found NO words
}
对h2ooooooo的答案进行了改进。处理搜索关键字的和/或。
答案 4 :(得分:0)
为此,我使用了一直用于此类问题的自定义功能。我会和你分享。
function in_array_stripos($needle_array, $word) {
foreach($needle_array as $needle) {
if (stripos($word, $needle) !== false) {
return true;
}
}
return false;
}
使用语法:
if (in_array_stripos(array('City', 'Weather'), $text)) {
// text contains these words
}