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? Link to comment https://forums.phpfreaks.com/topic/77847-solved-string-positions/ 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; ?> Link to comment https://forums.phpfreaks.com/topic/77847-solved-string-positions/#findComment-394033 Share on other sites More sharing options...
thiggins09 Posted November 18, 2007 Author Share Posted November 18, 2007 Thanks! Link to comment https://forums.phpfreaks.com/topic/77847-solved-string-positions/#findComment-394037 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.