关于strpos的问题。 如何获得第二个string的发生?

我明白这个函数会得到string的第一个出现。

但是我想要的是第二次出现。

如何去做呢?

您需要将search开始的偏移量指定为可选的第三个参数,并通过在第一次search后直接开始search来计算search结果,方法是将search的长度与search到的位置相加。

$pos1 = strpos($haystack, $needle); $pos2 = strpos($haystack, $needle, $pos1 + strlen($needle)); 

我知道这个问题是古老的,但这里有一个函数,我写了一个子string的第X次出现,这可能有助于其他人有这个问题,偶然发现这个线程。

 /** * Find the position of the Xth occurrence of a substring in a string * @param $haystack * @param $needle * @param $number integer > 0 * @return int */ function strposX($haystack, $needle, $number){ if($number == '1'){ return strpos($haystack, $needle); }elseif($number > '1'){ return strpos($haystack, $needle, strposX($haystack, $needle, $number - 1) + strlen($needle)); }else{ return error_log('Error: Value for parameter $number is out of range'); } } 

Smokey_Bud的recursion函数大大减缓了我的脚本。 在这种情况下使用正则expression式要快得多(用于查找任何事件):

 function strposX($haystack, $needle, $number) { { // decode utf8 because of this behaviour: https://bugs.php.net/bug.php?id=37391 preg_match_all("/$needle/", utf8_decode($haystack), $matches, PREG_OFFSET_CAPTURE); return $matches[0][$number-1][1]; } // get position of second 'wide' $pos = strposX('Hello wide wide world', 'wide', 2); 

你可以试试这个,虽然我还没有testing过,

 $pos = strpos($haystack, $needle, strpos($haystack, $needle)+strlen($needle)); 

简单即美

 function strposX($haystack, $needle, $n = 0) { $offset = 0; for ($i = 0; $i < $n; $i++) { $pos = strpos($haystack, $needle, $offset); if ($pos !== false) { $offset = $pos + strlen($needle); } else { return false; } } return $offset; } $offset = strposX($result, "\n", $n); if ($offset === false) { $offset = strlen($result) - 1; } 

一个替代的方式应该是爆炸string所需的字符,然后从数组中获取所需的索引

例如我有一个string

 $str = "hello-world-how-are-you-doing"; 

我需要在第四次出现“ – ”之后得到文本,也就是我想要“你”

我需要爆炸它使其成为一个数组

 $array = explode("-", $str); echo $array[4]; 

只是为我find如果是2或更多的一个字符的发生,然后通过strlen他们我发现存在2事件前(我不使用$匹配的所有):

 $string = '1234|6|#red'; if(strlen(preg_match_all('/|/', $string,$matches, PREG_OFFSET_CAPTURE)) ==2){ echo 'i have 2 occurence of char: |'; } 

请检查下面的代码…它对我来说工作得很好。

 <?php function f_srch ($s1, $par) { echo 'Searching for [' . $par . '] in [' . $s1 . ']<br>'; $k = 0; //while loop $i = 0; // counter while ($k >= 0) { $pos = strpos($s1, $par, $k); if ($pos === false) { $k=-1; echo 'Letter not found'.'<br>'; } else { if ($pos == $k) { echo 'The position of the letter is '.$pos.'<br>'; $i++; } $k++; } } echo 'The letter was found ' . $i . ' time(s).'.'<br>'; } f_srch('i am searching for a letter in this sentence','t'); ?> 

http://php.net/strpos

 $newstring = 'abcdef abcdef'; $pos = strpos($newstring, 'a', 1); // $pos = 7, not 0