Jump to content

Getting the position of X occurance of a char in a string


trink

Recommended Posts

I know that strpos gets the position of the first occurance of N character in a string and that strrpos gets the position of the last occurance of N character in a string.

But say I have a string that has 5 :'s in it.

a:b:d:c:e:f

How would i get the position of the Xth occurance, say, the 3rd.

I've been looking all around and havent really found anything, maybe I havent researched it extensively enough, I'm not to sure if there is a specific command to do that or not, but any help with this would be greatly appreciated.

see if this helps:

 

<?php
$text = 'This:is:a:text:i:used';
$nrChars = substr_count($text, ':');
$occurrence = 2; //the occurrence u want to print
for($i = 0; $i < $nrChars; $i++){
$pos = strpos($text, ':');
$length = strlen($text) - $pos;
$text = substr($text, $pos+1, $length);
if($i == $occurrence){
	echo $text . "<br />";
}
} 
?>

 

It will loop and modify the text so it will print only the occurrence. It is working correctly but it depends on what u want to achieve so feel free to modify it.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.