davidkierz Posted October 8, 2008 Share Posted October 8, 2008 how would i code a function that returns the text in $string between $start and $end not including $start and $end ?????? Quote Link to comment Share on other sites More sharing options...
Bendude14 Posted October 8, 2008 Share Posted October 8, 2008 can you be more specific? are you searching for words or characters? whats at the start and end? give us an example of what you want to start with and what you are trying to return? Quote Link to comment Share on other sites More sharing options...
davidkierz Posted October 8, 2008 Author Share Posted October 8, 2008 looking for a function that will do this $string = "adam baker charlie david edward frank"; $result = function($string, "baker", "david"); $result = charlie Quote Link to comment Share on other sites More sharing options...
davidkierz Posted October 8, 2008 Author Share Posted October 8, 2008 basically i am processing raw html to look for a certain string and since the html file changes everytime the script runs, i cant use substr directly i think i have to use a combination of substr and strpos but cat figure it out Quote Link to comment Share on other sites More sharing options...
Orio Posted October 8, 2008 Share Posted October 8, 2008 Two options... String functions or regex. Test both to see which one's faster: <?php $string = "adam baker charlie david edward frank"; $result1 = get_between1($string, "baker", "david"); $result2 = get_between2($string, "baker", "david"); echo $result1."<br>".$result2; function get_between1($str, $a, $b) { $pos_a = strpos($str, $a) + strlen($a); return trim(substr($str, $pos_a, strpos($str, $b) - $pos_a)); } function get_between2($str, $a, $b) { preg_match("/".preg_quote($a)."(.*?)".preg_quote($b)."/i", $str, $matches); return trim($matches[1]); } ?> Orio. Quote Link to comment Share on other sites More sharing options...
thebadbad Posted October 8, 2008 Share Posted October 8, 2008 Nice functions Orio, but you should add the second delimiter parameter to the preg_quote() functions, to deal with possible forward slashes in $string. Quote Link to comment Share on other sites More sharing options...
Orio Posted October 8, 2008 Share Posted October 8, 2008 Good point. In that case second function will become: <?php function get_between2($str, $a, $b) { preg_match("/".preg_quote($a, '/')."(.*?)".preg_quote($b, '/')."/i", $str, $matches); return trim($matches[1]); } ?> Orio. 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.