trink Posted August 27, 2007 Share Posted August 27, 2007 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. Quote Link to comment https://forums.phpfreaks.com/topic/66881-getting-the-position-of-x-occurance-of-a-char-in-a-string/ Share on other sites More sharing options...
effigy Posted August 27, 2007 Share Posted August 27, 2007 You could use a for loop or a regular expression. Will you only be pulling the position of one character or multiple? Are you trying to grab a delimited field? Quote Link to comment https://forums.phpfreaks.com/topic/66881-getting-the-position-of-x-occurance-of-a-char-in-a-string/#findComment-335256 Share on other sites More sharing options...
Fadion Posted August 27, 2007 Share Posted August 27, 2007 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. Quote Link to comment https://forums.phpfreaks.com/topic/66881-getting-the-position-of-x-occurance-of-a-char-in-a-string/#findComment-335301 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.