我在stackoverflow上找到了这个示例:
if (strpos($a,'are') !== false) {
echo 'true';
}
但是如何使其搜索两个词呢?我需要像这样的内容:如果$a包含单词"are"或"be"或两者都包含,则输出"contains"。
我尝试了使用异或和||。
只需分别检查这两个单词,并使用布尔运算符or
来检查$a
中是否包含其中一个或两个单词:
if (strpos($a,'are') !== false || strpos($a,'be') !== false) {
echo "contains";
}
$a
包含“are”,则不会执行第二个检查(用于“be”)。由于您还没有从所有的strpos答案中选择一个(其中大部分应该只适用于两个单词),请尝试使用我的函数,它超出了单词限制。它可以从较长的字符串中查找任意长度的单词(但不使用strpos)。我认为使用strpos,你需要知道单词的数量来确定应该使用多少||或利用循环(有点类似)。这种方法消除了所有这些,并为您提供了一种更灵活的重复使用代码的方式。我认为代码应该是灵活的、可重用的和动态的。测试一下,看看它是否符合您的要求!
function findwords($words, $search) {
$words_array = explode(" ", trim($words));
//$word_length = count($words_array);
$search_array = explode(" ", $search);
$search_length = count($search_array);
$mix_array = array_intersect($words_array, $search_array);
$mix_length = count($mix_array);
if ($mix_length == $search_length) {
return true;
} else {
return false;
}
}
//Usage and Examples
$words = "This is a long string";
$search = "is a";
findwords($words, $search);
// $search = "is a"; // returns true
// $search = "is long at"; // returns false
// $search = "long"; // returns true
// $search = "longer"; // returns false
// $search = "is long a"; // returns true
// $search = "this string"; // returns false - case sensitive
// $search = "This string"; // returns true - case sensitive
// $search = "This is a long string"; // returns true
$a = 'how are be';
if (strpos($a,'are') !== false || strpos($a,'be') !== false) {
echo 'contains';
}
尝试:
if (strpos($a,'are') !== false || strpos($a,'be') !== false)
echo 'what you want';
if ((strpos($a,'are') !== false) || (strpos($a, 'be') !==false) {
echo 'contains';
}
if ((strpos($a,'are') !== false) || (strpos($a,'be') !== false)) {
echo 'contains';
}
if (strpos($a,'are') !== false || strpost($a, 'be') !== false) {
echo "contains";
}
大脑糖果:如果第一个条件返回true,它将跳过第二个检查。因此两者都可以为真。如果第一个条件为false,则只有在这种情况下才会检查第二个条件。这被称为短路。if(strstr($a,'are') || strstr($a,'be')) echo 'contains';
if (strpos($a,'are') || strpos($a, 'be') {
echo 'contains';
}
strpos()
将返回0
,这将被评估为false
。使用其他人提出的!== false
。 - BenMorel
strpos()
函数定义它会返回false
如果未找到needle。因此,根据文档,您需要检查'非false'的情况。 - Veger