如何查找子字符串在母字符串中第N次出现的位置?

kbs_1983 2010-06-11 04:51:31
例如

abcdefghijkladgs

我要查询第二个a出现的位置,应该怎么写?
...全文
362 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
foolbirdflyfirst 2010-06-11
  • 打赏
  • 举报
回复
一顿饭的功夫,就结贴啦。。
还可以用正则函数
		$str = 'abcdefghijkladgs';

preg_match_all('#a#',$str,$m,PREG_OFFSET_CAPTURE);
$pos = 2;
print_r($m[0][$pos-1][1]);
tabris17 2010-06-11
  • 打赏
  • 举报
回复
$n = 2; //$n=3
$str = 'asdfghhasdfghsdfsdf';
$pos = -1;
for ($i = 0; $i < $n; $i++) {
$pos = strpos($str, 'a', $pos + 1);
if ($pos === false) break;
}
echo $pos;
kbs_1983 2010-06-11
  • 打赏
  • 举报
回复
谢谢kyzy_yy_pm~搞定了
kyzy_yy_pm 2010-06-11
  • 打赏
  • 举报
回复
改了下

function check($s, $s1, $n){
$s = '@'.$s;
$j = $x = $y = 0;
for($i = 0; $i < strlen($s); $i++){
if($index = strpos($s, $s1, $y? ($y + 1):$y)){
$j++;
if($j == $n){
$x = $index;
break;
}else{
$y = $index;
}
}
}
return $x - 1;
}
$s = 'afsdfhsafdfkljsldfj';
$s1 = 'f';
echo check($s, $s1, 2);
ghostwuboy 2010-06-11
  • 打赏
  • 举报
回复

$str = 'abcdefghijkladgsabcdefghijkladgs';
function getPos($str, $sonStr, $iIndex=0) {

static $aPos = array();
$ipos = false;
$ipos = strpos($str, $sonStr, $iIndex);
if ($ipos !== false) {

$aPos[count($aPos)] = $ipos;
getPos($str, $sonStr, $ipos+1);
}
return $aPos;
}
print_r(getPos($str, 'a'));

out:

Array
(
[0] => 0
[1] => 12
[2] => 16
[3] => 28
)


hfCoder 2010-06-11
  • 打赏
  • 举报
回复
不懂,up
liuahuilele 2010-06-11
  • 打赏
  • 举报
回复
恩啊

大体思路 也是楼上的
kyzy_yy_pm 2010-06-11
  • 打赏
  • 举报
回复

function check($s, $s1, $n){
$j = 0;
$x = 0;
$y = 0;
for($i = 0; $i < strlen($s); $i++){
if($index = strpos($s, $s1, $y + 1)){
$j++;
if($j == $n){
$x = $index;
break;
}else{
$y = $index;
}
}
}
return $x;
}
$s = 'afsdfhsafdfkljsldfj';
$s1 = 'f';
echo check($s, $s1, 2);

细节判断自己改改吧
foolbirdflyfirst 2010-06-11
  • 打赏
  • 举报
回复
搞错料,
可以explode('a',$str)切成数组,再算。
kbs_1983 2010-06-11
  • 打赏
  • 举报
回复
那如果是第三个a呢?例如
abcdefghijkladgsakk
谢谢~
foolbirdflyfirst 2010-06-11
  • 打赏
  • 举报
回复
		$str = 'abcdefghijkladgs';

echo strpos($str,'a',2);

21,886

社区成员

发帖
与我相关
我的任务
社区描述
从PHP安装配置,PHP入门,PHP基础到PHP应用
社区管理员
  • 基础编程社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧