Sop*_*ert 48
您需要将搜索开始的偏移量指定为可选的第三个参数,并通过在第一次出现后直接开始搜索来计算它,方法是将您要搜索的内容的长度添加到您找到的位置.
$pos1 = strpos($haystack, $needle);
$pos2 = strpos($haystack, $needle, $pos1 + strlen($needle));
Run Code Online (Sandbox Code Playgroud)
The*_*ent 46
我知道这个问题有点陈旧,但这是我写的一个函数,用于获取子串的第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');
}
}
Run Code Online (Sandbox Code Playgroud)
onc*_*ode 11
Smokey_Bud的递归函数大大减慢了我的脚本速度.在这种情况下使用正则表达式要快得多(用于查找任何出现):
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);
Run Code Online (Sandbox Code Playgroud)
要查找第二次出现的字符串,可以使用strpos和"offset"参数,方法是将前一个偏移量添加到strpos.
$source = "Hello world, how you doing world...world ?";
$find = "world";
$offset = 0;
$findLength = strlen($find);
$occurrence = 0;
while (($offset = strpos($source, $find, $offset))!== false) {
if ($occurrence ++) {
break;
}
$offset += $findLength;
}
echo $offset;
Run Code Online (Sandbox Code Playgroud)
您可以通过将偏移存储到数组中来查找所有实例
while (($offset = strpos($source, $find, $offset))!== false) {
$occurrences[] = $offset;
$offset += $findLength;
}
var_export($occurrences);
Run Code Online (Sandbox Code Playgroud)
或者可以通过匹配$ occurrence获得特定事件
//find 3rd occurrence
if ($occurrence ++ == 2) {
break;
}
Run Code Online (Sandbox Code Playgroud)
你可以试试这个,虽然我没有测试过 -
$pos = strpos($haystack, $needle, strpos($haystack, $needle)+strlen($needle));
Run Code Online (Sandbox Code Playgroud)