我在 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";
}
请注意,由于
or
运算符,如果第一个检查已显示 $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,它将跳过第二个检查。所以两者都可能是真的。如果第一个是假的,只有这样它才会检查第二个。这称为短路。
if(strstr($a,'are') || strstr($a,'be')) echo 'contains';
嗯,这样吗?
if (strpos($a,'are') || strpos($a, 'be') {
echo 'contains';
}
我会做这样的事情:
$string_vals = "jar,jar,binks";
$string_arr_jjb = explode(",", $string_vals);
foreach($string_arr as $string_arr_cur) {
if(strpos(whatever_usa_tryna_match-againsta, &string_arrcur) !== false)
}