考虑:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
假设我有上面的代码,如果($a包含“are”),写语句的正确方法是什么?
考虑:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
假设我有上面的代码,如果($a包含“are”),写语句的正确方法是什么?
当前回答
如果搜索不区分大小写,则使用strstr()或stristr(。
其他回答
为了找到一个“单词”,而不是出现一系列实际上可能是另一个单词的一部分的字母,以下是一个很好的解决方案。
$string = 'How are you?';
$array = explode(" ", $string);
if (in_array('are', $array) ) {
echo 'Found the word';
}
现在,使用PHP 8,您可以使用str_contains执行此操作:
if (str_contains('How are you', 'are')) {
echo 'true';
}
RFC
PHP 8之前
您可以使用strpos()函数,该函数用于查找一个字符串在另一个字符串中的出现:
$haystack = 'How are you?';
$needle = 'are';
if (strpos($haystack, $needle) !== false) {
echo 'true';
}
请注意,使用!==false是故意的(!=false或==true都不会返回期望的结果);strpos()返回大海捞针字符串开始时的偏移量,如果找不到针,则返回布尔值false。由于0是有效的偏移量,0是“false”,因此我们不能使用更简单的构造,如!strpos($a,'are')。
如果要避免“虚假”和“真实”问题,可以使用subst_count:
if (substr_count($a, 'are') > 0) {
echo "at least one 'are' is present!";
}
它比strpos慢一点,但它避免了比较问题。
可以通过三种不同的方式完成:
$a = 'How are you?';
1-stristr()
if (strlen(stristr($a,"are"))>0) {
echo "true"; // are Found
}
2-strpos()
if (strpos($a, "are") !== false) {
echo "true"; // are Found
}
3-preg_match()
if( preg_match("are",$a) === 1) {
echo "true"; // are Found
}
strpos函数工作得很好,但是如果您想对段落中的单词进行不区分大小写的检查,那么可以使用PHP的stripos函数。
例如
$result = stripos("I love PHP, I love PHP too!", "php");
if ($result === false) {
// Word does not exist
}
else {
// Word exists
}
查找字符串中不区分大小写的子字符串第一次出现的位置。
如果字符串中不存在该单词,则返回false,否则返回单词的位置。