PHP中判断字符串是否包含指定字符串有多种方法,下面介绍几种常用的方法:
1、strpos()函数
strpos()函数是PHP中最常用的判断字符串是否包含指定字符串的方法,该函数用于查找字符串在另一个字符串中第一次出现的位置,如果查找到,则返回字符串的位置,如果没有查找到,则返回false。使用方法如下:
$str = 'this is a string';
$findme = 'string';
$pos = strpos($str, $findme);
if ($pos === false) {
echo "The string '$findme' was not found in the string '$str'";
} else {
echo "The string '$findme' was found in the string '$str'";
echo " and exists at position $pos";
}
2、strstr()函数
strstr()函数也可以用来判断字符串是否包含指定字符串,该函数用于查找字符串在另一个字符串中第一次出现的位置,如果查找到,则返回从该位置到字符串结尾的所有字符,如果没有查找到,则返回false。使用方法如下:
$str = 'this is a string';
$findme = 'string';
$pos = strstr($str, $findme);
if ($pos === false) {
echo "The string '$findme' was not found in the string '$str'";
} else {
echo "The string '$findme' was found in the string '$str'";
echo " and exists at position $pos";
}
3、preg_match()函数
preg_match()函数也可以用来判断字符串是否包含指定字符串,该函数用于检测一个字符串是否匹配另一个字符串,如果匹配则返回1,否则返回0。使用方法如下:
$str = 'this is a string';
$findme = 'string';
if (preg_match("/$findme/", $str)) {
echo "The string '$findme' was found in the string '$str'";
} else {
echo "The string '$findme' was not found in the string '$str'";
}
4、str_replace()函数
str_replace()函数也可以用来判断字符串是否包含指定字符串,该函数用于替换字符串中的指定字符串,如果替换成功,则返回替换后的字符串,如果没有替换成功,则返回false。使用方法如下:
$str = 'this is a string';
$findme = 'string';
$pos = str_replace($findme, '', $str);
if ($pos === false) {
echo "The string '$findme' was not found in the string '$str'";
} else {
echo "The string '$findme' was found in the string '$str'";
echo " and exists at position $pos";
}
以上就是,可以根据自己的实际需要选择合适的方法。