1

if (strpos($text,'City') !== false)...

在那个“IF”行中,我想检查一些参数。例如“城市、天气等”我该怎么做?

编辑:谢谢大家的回答

4

5 回答 5

4
if(strpos($text,'City') !== false && strpos($text,'Weather') !== false && ...)

微不足道,真的。

于 2013-06-17T11:23:46.797 回答
2

您可以使用 in_array() 函数以另一种方式进行操作。

$array = array('City','Weather','anything');
if (in_array($text, $array)) {
    echo "Yes";
}
于 2013-06-17T11:29:51.693 回答
1

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
    }
?>
于 2013-06-17T11:28:29.267 回答
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的回答进行了一些改进。处理搜索关键字的 AND/OR。

于 2013-06-17T12:09:06.353 回答
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
}
于 2013-06-17T11:33:09.847 回答