tags:

views:

36

answers:

3

Pretty simple i'm sure, but..

I've got a file that is guaranteed to have only an <h1>some text</h1> and a <p>some more text</p> in it.

How would i go about returning these to elements as separate variables?

A: 

Your file is just text, so you're going to have to parse it. Generally HTML isn't all that suitable for parsing with normal operations, but if you know the exact contents you shouldn't have a problem.

Depending on what your separator is between the two tag blocks (let's pretend it's a \n, you could do something like this:

$contents = file_get_contents("yourfile.html");
list($h1,$p) = explode("\n",$contents);

That would give you the two text blocks in $h1 and $p. You could parse the rest from there if you needed to do more work.

zombat
What about this? `$contents = file_get_contents("yourfile.html");``list($h1,$p) = explode("</h1>",$contents);`
lfx
Well, that would remove the `</h1>` tag from the variable contents. I guess it depends on whether he wants the HTML tags as part of his variable content or not.
zombat
+2  A: 

If your file is an HTML one, the general solution would be to :

Pascal MARTIN
A: 

You can use something like this:

    function strBetween($au, $au2, $text) {//gets substring beetween $au and $au2 in $text
        $pau = strpos($text, $au);
        if($au2 !== '') {
            $pau2 = strpos($text, $au2,$pau);
            if($pau !== false && $pau2 !== false)
                return substr($text, $pau+strlen($au), $pau2-$pau-strlen($au));
            else
                return '';
        } else {
            return substr($text, $pau+strlen($au));
        }

    }
$contents = file_get_contents("yourfile.html");
$h1 = strBetween('<h1>', '</h1>', $contents);
$p = strBetween('<p>', '</p>', $contents);