考虑:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
假设我有上面的代码,如果($a包含“are”),写语句的正确方法是什么?
考虑:
$a = 'How are you?';
if ($a contains 'are')
echo 'true';
假设我有上面的代码,如果($a包含“are”),写语句的正确方法是什么?
当前回答
可以通过三种不同的方式完成:
$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
}
其他回答
Use:
$a = 'How are you?';
if (mb_strpos($a, 'are')) {
echo 'true';
}
它执行多字节安全strpos()操作。
您需要使用相同/不相同的运算符,因为strpos可以返回0作为其索引值。如果您喜欢三元运算符,请考虑使用以下运算符(我承认这有点倒退):
echo FALSE === strpos($a,'are') ? 'false': 'true';
查看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.";
}
strpos函数工作得很好,但是如果您想对段落中的单词进行不区分大小写的检查,那么可以使用PHP的stripos函数。
例如
$result = stripos("I love PHP, I love PHP too!", "php");
if ($result === false) {
// Word does not exist
}
else {
// Word exists
}
查找字符串中不区分大小写的子字符串第一次出现的位置。
如果字符串中不存在该单词,则返回false,否则返回单词的位置。
使用strstr()和stristr(()从字符串中查找单词出现的另一个选项如下:
<?php
$a = 'How are you?';
if (strstr($a,'are')) // Case sensitive
echo 'true';
if (stristr($a,'are')) // Case insensitive
echo 'true';
?>