PHP: find a string between two strings
April 10, 2011 15:56:07 Last update: April 10, 2011 15:56:07
This is a utility function to find a string between two other strings, such as the text between the
<title> tags in an HTML header.
<?php $s = '<html><head><title>Find it!</title></head><BODY>It works!</boDy></html>'; echo find_between($s, '<title>', '<//title>'), "\n"; echo find_between($s, '<title>', '</title>'), "\n"; echo find_tag_content($s, 'body'), "\n"; function find_between($s, $str1, $str2, $ignore_case = false) { $func = $ignore_case ? stripos : strpos; $start = $func($s, $str1); if ($start === false) { return ''; } $start += strlen($str1); $end = $func($s, $str2, $start); if ($end === false) { return ''; } return substr($s, $start, $end - $start); } function find_tag_content($s, $tag) { return find_between($s, "<$tag>", "</$tag>", true); } ?>