使用 stripos 函数在 PHP 中查找字符串
1。 stripos功能简介
PHP中有很多函数可以用来查找字符串,其中stripos函数是一个非常常用的函数。 stripos 函数可以查找字符串中另一个字符串的不区分大小写的出现。语法格式如下:
int stripos ( string $haystack , string $needle [, int $offset = 0 ] )
其中,$haystack 参数是要在其中搜索的字符串,$needle 参数是要在 $haystack 中搜索的字符串,可选的 $offset 参数表示在 $haystack 中从哪里开始搜索。默认值为 0。
2。找到字符串
的位置stripos 函数查找匹配字符串的第一个位置,并将该位置作为整数返回。如果没有找到,则返回 false。
$value = "Hello World!";
$position = stripos($value, "world");
if ($position === false) {
echo "Couldn't find the string";
} else {
echo "The string was found at position: " . $position;
}
执行上面的代码后,会输出:“The string was found atposition: 6”。这是因为值“world”首先出现在 $haystack 字符串中的位置 6 处。
3。找到几个匹配字符串的位置
您可以使用循环来查找 $haystack 字符串中与 $needle 字符串匹配的所有位置。下面的代码展示了如何查找字符串中多个匹配字符串的位置。
$value = "Hello World. Hi, John";
$search = array("world", "john");
foreach ($search as $s) {
$position = stripos($value, $s);
if ($position === false) {
echo "Couldn't find the string: " . $s . "
";
} else {
echo "The string " . $s . " was found at position: " . $position . "
";
}
}
运行上面的代码后,会输出:“The string world wasFound atposition:6”,“Thestringjohn wasfoundatposition:14”。
4。结合substr函数截取字符串
可以使用substr函数截断匹配字符串位置之后的字符串,从而得到匹配字符串之后的内容。
$value = "Hello World. Hi, John";
$search = "wor";
$position = stripos($value, $search);
if ($position === false) {
echo "Couldn't find the string: " . $search;
} else {
$result = substr($value, $position + strlen($search));
echo "The remaining string after " . $search . " is: " . $result;
}
执行上述代码后,会输出:“Theremainingstringafterworis:ld.HiJohn”。
5。安全敏感搜索字符串位置
与stripos函数相比,strpos函数区分大小写,并且还可以找到字符串的位置。语法与 stripos 函数完全相同,只是搜索时区分大小写。以下是使用 strpos 函数的示例:
$value = "Hello World!";
$position = strpos($value, "world");
if ($position === false) {
echo "Couldn't find the string";
} else {
echo "The string was found at position: " . $position;
}
由于strpos函数区分大小写,上面的代码将输出:“无法找到字符串”。
6。总结
在PHP中,查找字符串的函数是非常常用的。 stripos函数提供了一种非常方便实用的方法来判断一个字符串是否包含另一个字符串并返回匹配字符串的位置。无论您要查找单个字符串还是多个字符串,stripos 函数都可以胜任。可以使用 strpos 函数来执行区分大小写的搜索。我想在你日常的PHP开发中,stripos函数和strpos函数一定会是你的得力工具。
版权声明
本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。
code前端网