if (strpos($text,'City') !== false)
...
在那个“IF”行中,我想检查一些参数。例如“城市、天气等”我该怎么做?
编辑:谢谢大家的回答
if(strpos($text,'City') !== false && strpos($text,'Weather') !== false && ...)
微不足道,真的。
您可以使用 in_array() 函数以另一种方式进行操作。
$array = array('City','Weather','anything');
if (in_array($text, $array)) {
echo "Yes";
}
Kolinks 的答案是完全正确且非常琐碎的。如果您更喜欢使用数组,也可以这样做:
您的典型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
}
?>
$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的回答进行了一些改进。处理搜索关键字的 AND/OR。
为此,我使用了一个我一直用于解决此类问题的自定义函数。我会和你分享。
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
}