Forum Moderators: coopster

Message Too Old, No Replies

Get string from between tags in HTML/XML format

I can do it but there must be a better way!

         

surfgatinho

12:48 pm on Aug 22, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I've read an HTML/XML file into a string and I'm trying to extract the text from between a few sets of tags.

eg <tag1>Text I want</tag1>

I can do it but it seems really long winded. Is there a quick and easy way to do this maybe using reg expressions.
Also I only have access to standard libraries.

Thanks in advance
Chris

johannes

2:11 pm on Aug 22, 2003 (gmt 0)

10+ Year Member



I'm doing the same thing often. So I have a function for this, it's probably not very effective but it does the work. If somebody has a better solution, welcome!

Lets say you have:
$text="<tag1>Text I want</tag1>";

Then you can do the work with:
$textiwant=strip("<tag1>","</tag1>",$text,$pos=0);

My function:
function strip($f1,$f2,$text,&$pos){
if(!is_integer($pos)){$pos=false;return false;}
$pos1=strpos($text,$f1,$pos);
if(!is_integer($pos1)){$pos=false;return false;}
$pos1+=strlen($f1);
$pos2=strpos($text,$f2,$pos1);
if(!is_integer($pos2)){$pos=false;return false;}
$res=substr($text,$pos1,$pos2-$pos1);
$pos=$pos2+strlen($f2);
return $res;
}