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_get_contents('http://www.example.com');
$title = between($html,'<title>','</title>');

For more complex searches, you would need to use regular expressions.

5 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.

Unknown said...

It works with file_get_contents() because it returns the content of the file(or in this case the html source from the URL provided as a argument).
file() returns an array, containing each line from the file. That's why you can't pass it to the between() function.

jeancaffou said...

That is correct. Thanks!

Lavneet Sharma said...

Thanks a lot. I tried too hard building a web scrapper and this function helped me out very well.. :)

Vikas Saini said...

Thank you very much. I've been looking for this to integrate in feedWordpress wordpress plugin.