Feb 9, 2009

PHP: substring between two substrings in a string

Useful if you want to, for example get the text between HTML tags
 function between($s,$l,$r) {
  $il = strpos($s,$l,0)+strlen($l);
  $ir = strpos($s,$r,$il);
  return substr($s,$il,($ir-$il));
 }

//example
$html = file('http://www.example.com');
$title = between($html,'<title>','</title>');

1 comments:

Ameir Abdeldayem said...

I wasn't able to get your code to work as-is, but changing file to file_get_contents does the trick.