0

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?

0

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

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

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.