Posted By

jprochazka on 11/09/12


Tagged

strings


Versions (?)

Return a string between two strings or tags.


 / Published in: PHP
 

Returns the contents of a string between two unique strings. Useful for returning the portion of a string found between two tags such as and

  1. // String to extract string from.
  2. $string = 'This is a string to extract <tag>contents between tags</tag> from.';
  3.  
  4. // Call the function.
  5. echo extractString($string, '<tag>', '</tag>');
  6.  
  7. // Function that returns the string between two strings.
  8. function extractString($string, $start, $end) {
  9. $string = " ".$string;
  10. $ini = strpos($string, $start);
  11. if ($ini == 0) return "";
  12. $ini += strlen($start);
  13. $len = strpos($string, $end, $ini) - $ini;
  14. return substr($string, $ini, $len);
  15. }
  16.  
  17. // Value Echoed: contents between tags

Report this snippet  

You need to login to post a comment.