Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about strpos: how to get 2nd occurrence of a string?

Tags:

string

php

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?

like image 749
vfvg Avatar asked Jun 27 '10 03:06

vfvg


People also ask

Where is second occurrence of a character in a string PHP?

Simplest solution for this specific case is to use the offset parameter: $pos = strpos($info, '-', strpos($info, '-') + 1);

What is strpos ()? Give example?

The strpos() function finds the position of the first occurrence of a string inside another string. Note: The strpos() function is case-sensitive. Note: This function is binary-safe.

What is the strpos () function used for?

strpos in PHP is a built-in function. Its use is to find the first occurrence of a substring in a string or a string inside another string. The function returns an integer value which is the index of the first occurrence of the string.

How will you locate a string within a string?

Search for string inside another string - strstrThe function strstr returns the first occurrence of a string in another string. This means that strstr can be used to detect whether a string contains another string.


2 Answers

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.

/**  * 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');     } } 

Or a simplified version:

function strposX($haystack, $needle, $number = 0) {     return strpos($haystack, $needle,         $number > 1 ?         strposX($haystack, $needle, $number - 1) + strlen($needle) : 0     ); } 
like image 80
TheKidsWantDjent Avatar answered Sep 20 '22 22:09

TheKidsWantDjent


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)); 
like image 44
Sophie Alpert Avatar answered Sep 19 '22 22:09

Sophie Alpert