PHP中的strpos()和stripos()函数
这些函数用于查找字符串中任何子字符串的位置。在此,strpos()区分大小写,stripos()而不区分大小写。
PHP-strpos()函数
此函数用于查找字符串中任何子字符串的第一个匹配项。此函数返回一个整数值,该整数值是给定子字符串首次出现的起始索引。
注意:strpos()区分大小写。
语法:
strpos(string, substring, [intial_pos]);
这里,
string–是原始字符串,即我们要在其中搜索子字符串的源字符串。
substring–是要在字符串中搜索的字符串。
[initial_pos]–这是一个可选参数,可用于定义起始位置,从该位置开始搜索子字符串。
返回类型:函数strpos()返回一个整数值,该值将是字符串中子字符串的索引。
PHP代码
<?php
//查找字符串中的子字符串的功能
//参数
//$sub_str-要搜索的字符串
//$str-我们必须在其中输入的主字符串
//找到子字符串
function searchSubstring($sub_str, $str){
//调用函数,这里第三个参数是
//可选-我们指定的0表示
//搜索应从第0个索引开始
$pos = strpos($str, $sub_str, 0);
return $pos;
}
//测试给定功能的主代码
//在字符串中查找子字符串
$main_string = "Hello world, how are you?";
$sub_string = "how";
//位置将存储在$index-
$index = searchSubString($sub_string, $main_string);
if($index == null){
echo $sub_string." does not exists in the string";
}
else{
echo $sub_string." found at ".$index. " position";
}
?>输出结果
how found at 13 position
PHPstripos()方法
此功能与相同strpos(),除大小写外所有操作均相同,此功能不检查大小写敏感性。stripos()在字符串中找到任何子字符串时忽略大小写。
示例:参考上面的代码并搜索“HOW”
参考:https://www.w3schools.com/php/func_string_strpos.asp