php 关于 strpos 的问题:如何获得第二次出现的字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3126324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Question about strpos: how to get 2nd occurrence of a string?
提问by vfvg
I understand that this function will get the first occurrence of the string.
我知道这个函数会得到字符串的第一次出现。
But what I want is the 2nd occurrence.
但我想要的是第二次出现。
How to go about doing that?
怎么做呢?
回答by Sophie Alpert
You need to specify the offset for the start of the search as the optional third parameter and calculate it by starting the search directly after the first occurrence by adding the length of what you're searching for to the location you found it at.
您需要将搜索开始的偏移量指定为可选的第三个参数,并通过在第一次出现后直接开始搜索来计算它,方法是将您要搜索的内容的长度添加到您找到它的位置。
$pos1 = strpos($haystack, $needle);
$pos2 = strpos($haystack, $needle, $pos1 + strlen($needle));
回答by TheKidsWantDjent
I know this question is kind of old, but here's a function I wrote to get the Xth occurrence of a substring, which may be helpful for other people that have this issue and stumble over this thread.
我知道这个问题有点老了,但这是我编写的一个函数,用于获取第 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');
}
}
回答by oncode
The recursive function from Smokey_Bud was slowing my script drastically down. Using a regular expression is much faster in this case (for finding any occurence):
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);
回答by Sadat
You can try this, though I haven't tested it out-
你可以试试这个,虽然我还没有测试过——
$pos = strpos($haystack, $needle, strpos($haystack, $needle)+strlen($needle));
回答by Tofeeq
To find second occurrence of the string you can use the strposalong with "offset" parameter, by adding previous offset to strpos.
要查找字符串的第二次出现,您可以将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;
You can find all the occurrences by storing offset into an array
您可以通过将偏移量存储到数组中来找到所有出现的次数
while (($offset = strpos($source, $find, $offset))!== false) {
$occurrences[] = $offset;
$offset += $findLength;
}
var_export($occurrences);
Or can get a specific occurrence by matching $occurrence
或者可以通过匹配 $occurrence 来获取特定事件
//find 3rd occurrence
if ($occurrence ++ == 2) {
break;
}
回答by tom10271
Simple is beautiful
简单即美
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;
}
回答by Maarten Wolzak
Old question but how about using explode?
老问题,但如何使用explode?
$corpus = "how many words are there in a dictionary? I'm not going to count them word by word...";
$looking_for = 'word';
$instance = 2;
$parts = explode($looking_for, $corpus, $instance + 1);
array_pop($parts);
$position = strlen(implode($looking_for, $parts));
回答by Hamze GhaemPanah
Easily, just do it:
很容易,只需这样做:
$i = $pos = 0;
do {
$pos = strpos( $string, $needle, $pos+1 );
} while( $i++ < $nth);
$nth for your situation is equal to 2.
您的情况的 $nth 等于 2。
回答by Dan
just worked for me to find if are 2 or more occurrence of a char, then by strlen them i found that exist 2 occurrence ex ( i dont use $matches at all):
只是为我工作以查找是否有 2 次或更多次出现一个字符,然后通过 strlen 他们我发现存在 2 次出现前(我根本不使用 $matches):
$string = '1234|6|#red';
if(strlen(preg_match_all('/|/', $string,$matches, PREG_OFFSET_CAPTURE)) ==2){
echo 'i have 2 occurence of char: |';
}
回答by Kad
function substr_Index( $str, $nth ){
$str2 = '';
$posTotal = 0;
for($i=0; $i < $nth; $i++){
if($str2 != ''){
$str = $str2;
}
$pos = strpos($str, ':');
$str2 = substr($str, $pos+1);
$posTotal += $pos+1;
}
return $posTotal-1;
}
echo substr($mystring, substr_Index( $mystring , 2) );
Function returns position of nth delimiter.
函数返回第 n 个分隔符的位置。
Second parameter of substr_Indexmust be bigger than 0;
的第二个参数substr_Index必须大于0;
To find second occourance use substr_Index( $mystring , 2)
找到第二次出现使用 substr_Index( $mystring , 2)

