Paul EC1 Posted July 7, 2008 Share Posted July 7, 2008 Hi All, I have no idea how to achieve this and your help would be very much appreciated. Firstly, I am looking to find the first instance of a letter in a string. e.g. $str = “today is a nice day” $find = “a” Result = the first instance of $find = position 4 And secondly I am looking to find the secound instance of a letter in a string. e.g. $str = “today is a nice day” $find = “a” Result = the secound instance of $find = position 10 Many many thanks Paul Link to comment https://forums.phpfreaks.com/topic/113642-first-instance-of-a-letter-in-a-string/ Share on other sites More sharing options...
br0ken Posted July 7, 2008 Share Posted July 7, 2008 If you want this to work regardless of the case you will need to use strtolower() around $var in the substr() function. <?php $var = "This is a sentence"; $letter = "e"; // First occurence echo substr($var, strpos($var, $letter), 1); // Second occurence echo substr($var, strpos($var, $letter, strpos($var, $letter)), 1); ?> Link to comment https://forums.phpfreaks.com/topic/113642-first-instance-of-a-letter-in-a-string/#findComment-584000 Share on other sites More sharing options...
Barand Posted July 7, 2008 Share Posted July 7, 2008 try <?php function char_positions($needle, $haystack, $caseinsens = 0) { if ($caseinsens) { $needle = strtolower($needle); $haystack = strtolower($haystack); } $arr = str_split($haystack); return array_keys($arr, $needle); } $str = 'today is a nice day'; $find = 'a'; $positions = char_positions($find, $str); echo "\"$find\" found at positions " . join (', ', $positions); //--> "a" found at positions 3, 9, 17 ?> Link to comment https://forums.phpfreaks.com/topic/113642-first-instance-of-a-letter-in-a-string/#findComment-584015 Share on other sites More sharing options...
Paul EC1 Posted July 7, 2008 Author Share Posted July 7, 2008 Many thanks for that, it works vey well. But!!! say THAT i wanted the instacne of the letter to be a Variable e.g. find the five occurrence or the 10 occurrence in other words the occurrence to be $occurrence Link to comment https://forums.phpfreaks.com/topic/113642-first-instance-of-a-letter-in-a-string/#findComment-584036 Share on other sites More sharing options...
Barand Posted July 7, 2008 Share Posted July 7, 2008 It returns an array of all the positions where $find occurs so you just pick the one/s you want. Link to comment https://forums.phpfreaks.com/topic/113642-first-instance-of-a-letter-in-a-string/#findComment-584038 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.