thiggins09 Posted November 18, 2007 Share Posted November 18, 2007 What would be the best way to get the closest occurrence of a given string before a given position? For example $x='aaCaBaaaCaaaBaB' If you wanted to find the position of the closest C, before the second to last B, (position 12), how would you go about doing that? Quote Link to comment Share on other sites More sharing options...
GingerRobot Posted November 18, 2007 Share Posted November 18, 2007 I'd reverse the string, find the first occurence after the given offset, then work out the position in the unreversed string: <?php $str = 'aaCaBaaaCaaaBaB'; $char = 'C'; $start = 12;//the position of second to last B $start_rev = strlen($str) - 1 - $start;//position of character in reversed string $str_rev = strrev($str); $pos = strpos($str_rev,$char,$start_rev); $original_pos = strlen($str) - 1 - $pos;//the position of the character in the original string. echo 'The first occurence of '.$char.' before the character at position '.$start. ' is at postion '. $original_pos; ?> Quote Link to comment Share on other sites More sharing options...
thiggins09 Posted November 18, 2007 Author Share Posted November 18, 2007 Thanks! Quote Link to comment 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.