如何查找子字符串在母字符串中第N次出现的位置? 例如abcdefghijkladgs我要查询第二个a出现的位置,应该怎么写? 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 $str = 'abcdefghijkladgs'; echo strpos($str,'a',2); 那如果是第三个a呢?例如abcdefghijkladgsakk谢谢~ 搞错料,可以explode('a',$str)切成数组,再算。 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);细节判断自己改改吧 改了下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); $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) $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; 一顿饭的功夫,就结贴啦。。还可以用正则函数 $str = 'abcdefghijkladgs'; preg_match_all('#a#',$str,$m,PREG_OFFSET_CAPTURE); $pos = 2; print_r($m[0][$pos-1][1]); PHP查询问题,求最佳答案 关于cookie的问题 gb2312改成utf-8编码需要做哪些修改? 来源关键词记录,在线等 关于数据库操作类的一个问题,$query = $db->query($sql) 使用Php或是wordpress程序做一个搜索框 javascript中关于函数里取值的问题 请问php+mysql问题?(续) PHP 页面不能与数据库同步刷新的问题 问题 memcache没状态了 Mysql INT型 自动增长,为什么1后是11,2后是22?
echo strpos($str,'a',2);
abcdefghijkladgsakk
谢谢~
可以explode('a',$str)切成数组,再算。
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);细节判断自己改改吧
$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);
$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
)
$str = 'asdfghhasdfghsdfsdf';
$pos = -1;
for ($i = 0; $i < $n; $i++) {
$pos = strpos($str, 'a', $pos + 1);
if ($pos === false) break;
}
echo $pos;
还可以用正则函数
$str = 'abcdefghijkladgs';
preg_match_all('#a#',$str,$m,PREG_OFFSET_CAPTURE);
$pos = 2;
print_r($m[0][$pos-1][1]);