Return a string between two strings or tags.


/ Published in: PHP
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.