Jump to content

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


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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.