考虑:
$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(。
其他回答
您应该使用不区分大小写的格式,因此如果输入的值是小写或大写,则无所谓。
<?php
$grass = "This is pratik joshi";
$needle = "pratik";
if (stripos($grass,$needle) !== false) {
/*If i EXCLUDE : !== false then if string is found at 0th location,
still it will say STRING NOT FOUND as it will return '0' and it
will goto else and will say NOT Found though it is found at 0th location.*/
echo 'Contains word';
}else{
echo "does NOT contain word";
}
?>
在这里,stripos在不考虑箱子(小/帽)的情况下,在heystack中找到了针头。
带输出的PHPCode样本
您还可以使用内置函数strchr()和strrchr()以及多字节字符串mb_strchr(()和mb_strrchr(()的扩展。这些函数返回部分字符串,如果找不到,则返回FALSE。
strchr()-查找字符串的第一次出现(是strstr()的别名)。strrchr()-查找字符串中最后出现的字符。
要确定一个字符串是否包含另一个字符串,可以使用PHP函数strpos()。
int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )`
<?php
$haystack = 'how are you';
$needle = 'are';
if (strpos($haystack,$needle) !== false) {
echo "$haystack contains $needle";
}
?>
警告:
如果您正在搜索的针位于干草堆的开始位置,它将返回位置0,如果您进行==比较,但这不起作用,则需要执行===
A==符号是一个比较,用于测试左侧的变量/表达式/常量是否与右侧的变量/表达/常量具有相同的值。
A==符号是比较两个变量/表达式/常量是否相等并且具有相同的类型,即两者都是字符串或两者都是整数。
使用这种方法的优点之一是,与str_contains()不同,每个PHP版本都支持此函数。
现在,使用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')。
查看strpos():
<?php
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);
// Note our use of ===. Simply, == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'.";
} else {
echo "The string '$findme' was found in the string '$mystring',";
echo " and exists at position $pos.";
}