×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
1
Language: PHP
Posted by: Jeremy Brown
Added: Dec 31, 2015 5:23 PM
Views: 22
Search $string and return what's between $start and $end. It's simple, doesn't use regex, so it's just a useful cleaver to pick up when you need to extract some content but it's not in a structured format (but you know it's the bit that comes between, say: '</head>' and '<div id="footer">' OR between 'Amy says' and 'Do not tell a soul'). You can use this to salvage nodes from an XML file that won't parse, or any number of things.
  1. /**
  2.  * Search a string for a substring between $start and $end substrings
  3.  */
  4. function get_string_between($string, $start, $end, $inclusive = FALSE) {
  5.     /* for convenience, we make our string start at position #1 */
  6.     $string = ' ' . $string;
  7.    
  8.     $string = htmlentities($string);
  9.     $start = htmlentities($start);
  10.     $end = htmlentities($end);
  11.    
  12.     /* initial point = position of start delimiter */
  13.     $ini = strrpos($string, $start);
  14.     /* if start not found, return null */
  15.     if ($ini == 0) {
  16.         return "";
  17.     }
  18.     /* the actual initial point should just after the start delimiter */
  19.     $ini += strlen($start);
  20.  
  21.     /* the length of the string we're seeking
  22.      * is distance between the start and end delimiters, minus the start delimiter's length
  23.      */
  24.     $len = strrpos($string, $end, $ini) - $ini;
  25.  
  26.     /* if "inclusive" then tack the delims onto the found string */
  27.     $ret = substr($string, $ini, $len);
  28.     if ($inclusive) {
  29.         $ret = $start . $ret . $end;
  30.     }
  31.     return html_entity_decode($ret);
  32. }