详情页

PHP检测是否存在指定字符串

时间:2023年10月04日

编辑:佚名

在 PHP 中,您可以使用内置的字符串函数 strpos() 来检查字符串中是否存在指定的字符串。
下面是使用 strpos() 函数检测指定字符串是否存在的示例代码:
$findString='sample';
$myString='This is a sample string';
if(strpos($myString, $findString) !== false){
echo "The string '$findString' was found in the string '$myString'.";
}
else{
echo "The string '$findString' was not found in the string '$myString'.";  
}
在这个例子中,strpos() 函数接受两个参数,第一个是要检查的字符串,第二个是要查找的字符串。如果指定的字符串找到,则返回第一次出现的位置索引。如果未找到指定字符串,则返回 false。因此,我们使用了 !== 运算符来确保返回的位置索引不等于 false。
如果 $findString 存在于 $myString 中,那么将会输出 “The string ‘sample’ was found in the string ‘This is a sample string’.”。否则,将会输出 “The string ‘sample’ was not found in the string ‘This is a sample string’.”。
相关文章
猜你需要