PHP中有“if in”运算符吗?

2 投票
4 回答
1091 浏览
提问于 2025-04-16 14:10

我在找一种方法,检查一个字符串是否存在于另一个字符串里面,就像在Python中那样:

print "a" in "aloha"

这会返回1

4 个回答

1

尝试一下

$mystring = 'aloha';
$findme   = 'a';
$pos = strpos($mystring, $findme);
echo $pos // return 0 

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";
}
3

strpos()

$pos = strpos("aloha", "a");

编辑

你可以通过使用 IF 来检查字符串是否存在,像这样:-

if (strpos("aloha", "a") !== false) {
     echo "The string was found";

} else {
     echo "The string was not found";
}
2
strpos("aloha", "a") !== false

这个代码会返回一个布尔值,意思是字母"a"是否在单词"aloha"里面。

注意:使用!==是很重要的,而不是!=,因为在PHP中0 == false是成立的。

撰写回答