查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。

本教程操作环境:windows7系统、PHP8.1版、DELL G3电脑
在PHP中,想要查找字符串,判断是第几位有两种函数:
strpos()
stripos()
立即学习“PHP免费学习笔记(深入)”;
这两种函数都可以查找字符串首次出现的位置,语法也类似:
strpos(string,find,start) stripos(string,find,start)
| 参数 | 描述 |
|---|---|
| string | 必需。规定被搜索的字符串。 |
| find | 必需。规定要查找的字符。 |
| start | 可选。规定开始搜索的位置。 |
返回值:返回字符串在另一字符串中第一次出现的位置,如果没有找到字符串则返回 FALSE。
但strpos()函数区分大小写,而stripos()函数不区分大小写。
因为字符串是从0开始计数的,因此strpos()和stripos()函数获取的位置需要进行加1处理。
示例1:使用strpos()函数查找字符串是第几位
<?php
header('content-type:text/html;charset=utf-8');
$mystring = 'ABCabc';
$findme1 = 'c';
$pos1 = strpos($mystring, $findme1)+1;
echo $findme1." 在第 ".$pos1." 位<br>";
$findme2 = 'C';
$pos2 = strpos($mystring, $findme2)+1;
echo $findme2." 在第 ".$pos2." 位<br>";
$findme3 = 'Ca';
$pos3 = strpos($mystring, $findme3)+1;
echo $findme3." 在第 ".$pos3." 位<br>";
?>
示例2:使用stripos()函数查找字符串是第几位
<?php
header('content-type:text/html;charset=utf-8');
$mystring = 'ABCabc';
$findme1 = 'c';
$pos1 = stripos($mystring, $findme1)+1;
echo $findme1." 在第 ".$pos1." 位<br>";
$findme2 = 'C';
$pos2 = stripos($mystring, $findme2)+1;
echo $findme2." 在第 ".$pos2." 位<br>";
$findme3 = 'aB';
$pos3 = stripos($mystring, $findme3)+1;
echo $findme3." 在第 ".$pos3." 位<br>";
?>
推荐学习:《PHP视频教程》
以上就是php怎么查找字符串是第几位的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号