4种方法:1、用stripos()查找子串的出现位置,语法“stripos($str,$find)”;2、用strripos()查找子串的的出现位置,语法“strripos($str,$find)”;3、用strpos()查找子串的出现位置,语法“strpos($str,$find)”;4、用strrpos()查找子串的出现位置,语法“strrpos($str,$find)”。
本教程操作环境:windows7系统、php8.1版、dell g3电脑
在进行字符串查找操作时,有时会要求在某一字符串中查找指定的子字符串(简称子串),看看该子串是否存在于这个字符串中。
我们一般会通过使用php内置函数来查找这个子串在字符串的第一次或最后一次的出现位置来进行判断。而查找字符串有两种情况:一种是对大小写不敏感,即不区分大小写的查找;另外一种是对大小写敏感,即区分大小写的查找。
情况一:判断子串是不是存在(大小写不敏感)
大小写不敏感的检测子串是不是存在,需要使用stripos()和strripos()函数。
stripos()和strripos()函数都可以大小写不敏感的检查指定子串的出现位置,如果返回值为false,则指定子串不存在。
因此我们就可以使用以下代码来判断子串是不是存在
<?phpheader("content-type:text/html;charset=utf-8");$string = "abcdcbabcd";$findme = "bc";if(stripos($string, $findme)!=false){ echo "子串 “'$findme'” 在字符串 “'$string'” 中存在。";}else{ echo "子串 “'$findme'” 在字符串 “'$string'” 中不存在。";}if(strripos($string, $findme)!=false){ echo "<br>子串 “'$findme'” 在字符串 “'$string'” 中存在。";}else{ echo "<br>子串 “'$findme'” 在字符串 “'$string'” 中不存在。";}?>
输出结果:
说明:stripos()和strripos()函数
stripos($string,$find,$start)函数可以查找字符串在另一字符串中第一次出现的位置(不区分大小写)。
strripos($string,$find,$start)函数可以查找字符串在另一字符串中最后一次出现的位置(不区分大小写)。
这两个函数的参数是相似的,都接受两个必需参数$string和$find,一个可省略参数$start。
$string参数:用于指定要被查找的字符串。
$find参数:用于指定要查找的子串,可以包含一个或者多字符。(如果不是字符串类型,那么它将被转换为整型并被视为字符顺序值)。
$start参数:用于指定从$string 中的哪个字符开始查找,返回的位置数字值仍然相对于 $string 的起始位置。
情况2:检测子串是不是存在(大小写敏感)
大小写敏感的检测子串是不是存在,需要使用strpos()和strrpos()函数。
strpos()和strrpos()函数可以大小写敏感的检查指定子串的出现位置,如果返回值为false,则指定子串不存在。
示例:
<?phpheader("content-type:text/html;charset=utf-8");$string = "abcdcbabcd";$findme1 = "bc";$findme2 = "bc";$pos1 = strpos($string, $findme1);$pos2 = strrpos($string, $findme1);$pos3 = strpos($string, $findme2);$pos4 = strrpos($string, $findme2);if($pos1 !=false){ echo "子串 '$findme1' 在字符串 '$string' 中存在。";}else{ echo "子串 '$findme1' 在字符串 '$string' 中不存在。";}if($pos2 !=false){ echo "<br>子串 '$findme1' 在字符串 '$string' 中存在。";}else{ echo "<br>子串 '$findme1' 在字符串 '$string' 中不存在。";}if($pos3 !=false){ echo "<br>子串 '$findme2' 在字符串 '$string' 中存在。";}else{ echo "<br>子串 '$findme2' 在字符串 '$string' 中不存在。";}if($pos4 !=false){ echo "<br>子串 '$findme2' 在字符串 '$string' 中存在。";}else{ echo "<br>子串 '$findme2' 在字符串 '$string' 中不存在。";}?>
strpos()和strrpos()函数会区分大小写的在字符串$string中查找子串$findme1或者$findme2。当完全匹配上,存在子串时,会返回子串在字符串的第一次或最后一次的出现位置;如果在字符串的没有找到子串,则返回false。
从上面的例子可以看出,只有子串"bc"和字符串“abcdcbabcd”是完全匹配,子串"bc"被认为是存在于字符串“abcdcbabcd”中的。因此输出结果为:
说明:strpos()和strrpos()函数
strpos($string,$find,$start)函数可以返回子字符串首次出现的位置(区分大小写);
strrpos($string,$find,$start)函数可以返回子字符串最后一次出现的位置(区分大小写);
strpos()和strrpos()函数相似,都接受两个必需参数$string(被查找的字符串)和$find(要查找的子串),一个可省略参数$start(查找的开始位置)。注:字符串位置起始于 0,而不是 1。
<?phpheader("content-type:text/html;charset=utf-8");$string = "abcabcabcabc";$findme1 = "c";$findme2 = "c";echo "子串 '$findme1' 第一次出现的位置:".strpos($string, $findme1);echo "<br>子串 '$findme1' 最后一次出现的位置:".strrpos($string, $findme1);echo "<br>子串 '$findme2' 第一次出现的位置:".strpos($string, $findme2);echo "<br>子串 '$findme2' 最后一次出现的位置:".strrpos($string, $findme2);?>
输出结果:
推荐学习:《php视频教程》
以上就是php怎么检测子字符串是否存在的详细内容。