solepixel Posted September 8, 2008 Share Posted September 8, 2008 I'm trying to figure out how to loop through a string similar to a directory structure, such as /boom/stuff/test/file/check/ and I want to break off the last chunk on each look, then check that in a database until it finds something in the database, or runs out of string, so it should be: /boom/stuff/test/file/check/ - 0 rows /boom/stuff/test/file/ - 0 rows /boom/stuff/test/ - 0 rows /boom/stuff/ - 0 rows /boom/ - 0 rows / - 0 rows break; - no rows found at all. or /boom/stuff/test/file/check/ - 0 rows /boom/stuff/test/file/ - 0 rows /boom/stuff/test/ - 0 rows /boom/stuff/ - 1 row break; - found 1 row with /boom/stuff/ Does that make sense? Thanks. Link to comment https://forums.phpfreaks.com/topic/123202-looping-through-string-until-string-is-empty/ Share on other sites More sharing options...
solepixel Posted September 8, 2008 Author Share Posted September 8, 2008 Right now, i ended up doing this. Is there a better way anyone knows of? if(strstr($check,"/")){ $check = (substr($check,-1) == "/") ? substr($check,0,-1) : $check; $check = substr($check,0,strrpos($check,"/")+1); } Link to comment https://forums.phpfreaks.com/topic/123202-looping-through-string-until-string-is-empty/#findComment-636306 Share on other sites More sharing options...
Ken2k7 Posted September 8, 2008 Share Posted September 8, 2008 Is it in string format? Try this: <?php function func ($dir_string) { while (strlen($dir_string) > 1 && ($last_pos = strrpos($dir_string, "/")) !== false) { // database check here // return a value if row is not 0. Don't use break! $dir_string = substr($dir_string, 0, -1); $dir_string = substr($dir_string, 0, strrpos($dir_string, "/") + 1); } // return a value if no matches are found } ?> Link to comment https://forums.phpfreaks.com/topic/123202-looping-through-string-until-string-is-empty/#findComment-636331 Share on other sites More sharing options...
kenrbnsn Posted September 8, 2008 Share Posted September 8, 2008 You could use the array_pop() function here: <?php $str = '/boom/stuff/test/file/check/'; $test_ary = explode('/',trim($str,'/')); while (!empty($test_ary)) { echo '/' . implode('/',$test_ary) . '/<br>'; $dmy = array_pop($test_ary); } echo '/<br>'; ?> Ken Link to comment https://forums.phpfreaks.com/topic/123202-looping-through-string-until-string-is-empty/#findComment-636454 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.