考虑:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
假设我有上面的代码,如果($a包含“are”),写语句的正确方法是什么?
考虑:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
假设我有上面的代码,如果($a包含“are”),写语句的正确方法是什么?
当前回答
strpos函数工作得很好,但是如果您想对段落中的单词进行不区分大小写的检查,那么可以使用PHP的stripos函数。
例如
$result = stripos("I love PHP, I love PHP too!", "php");
if ($result === false) {
// Word does not exist
}
else {
// Word exists
}
查找字符串中不区分大小写的子字符串第一次出现的位置。
如果字符串中不存在该单词,则返回false,否则返回单词的位置。
其他回答
Use:
$a = 'How are you?';
if (mb_strpos($a, 'are')) {
echo 'true';
}
它执行多字节安全strpos()操作。
这里有一个小的实用函数,在这种情况下很有用
// returns true if $needle is a substring of $haystack
function contains($needle, $haystack)
{
return strpos($haystack, $needle) !== false;
}
如果只想检查一个字符串是否包含在另一个字符串中,请不要使用preg_match()。改用strpos()或strstr(),因为它们会更快。(http://in2.php.net/preg_match)
if (strpos($text, 'string_name') !== false){
echo 'get the string';
}
许多使用subst_count的答案会检查结果是否大于0。但由于if语句将零视为false,因此可以避免该检查并直接写入:
if (substr_count($a, 'are')) {
若要检查是否不存在,请添加!操作员:
if (!substr_count($a, 'are')) {
可以使用以下函数检查字符串:
function either_String_existor_not($str, $character) {
return strpos($str, $character) !== false;
}