Text Between Strings PHP

here’s a useful function that I found in the comments of a php.net function reference to quickly extract the text between two given strings, useful for parsing XML documents or HTML. I’ve used it to parse lotto results, XML favorites and grabbing <img> links by fopen’ing a HTML file.
$text is the string you want to parse
$s1 is the start string
$s2 is the end string

function get_between ($text, $s1, $s2) {
$mid_url = "";
$pos_s = strpos($text,$s1);
$pos_e = strpos($text,$s2);
for ( $i=$pos_s+strlen($s1) ; (( $i<($pos_e)) && $i < strlen($text)) ; $i++ ) {
$mid_url .= $text[$i];
}
return $mid_url;
}

for example if this is a string in the variable $line in a file you are parsing
“<img>http://www.imageurl.com/image.gif</img>”
you can extract the url by using the function like this

$imageurl=get_between($line,"<img>","</img>");

About Andy

This is my personal website where I (occasionally) post about things going on in the world of me. I am the creator of CommentLuv and administrator of comluv.com
Code , , , , ,

0 responses to Text Between Strings PHP


  1. bernardo amoeim

    but how can i make loop throug a hole file and put the results into an arry so i can export in into an XML?