tags:

views:

93

answers:

3

Possible Duplicate:
Best methods to parse HTML

Hello!

How can I parse HTML code held in a PHP variable if it something like:

<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG!

I want to only get the text that's between the headings and I understand that it's not a good idea to use Regular Expressions.

Help! :)

Thank you.

+2  A: 

Dom Extension

nikic
+4  A: 

Use PHP Document Object Model:

<?php
   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   $DOM = new DOMDocument;
   $DOM->loadHTML($str);

   //get all H1
   $items = $DOM->getElementsByTagName('h1');

   //display all H1 text
   for ($i = 0; $i < $items->length; $i++)
        echo $items->item($i)->nodeValue . "<br/>";
?>

This outputs as:

 T1
 T2
 T3

[EDIT]: After OP Clarification:

If you want the content like Lorem ipsum. etc, you can directly use this regex:

<?php
   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   echo preg_replace("#<h1.*?>.*?</h1>#", "", $str);
?>

this outputs:

Lorem ipsum.The quick red fox...... jumps over the lazy brown FROG

shamittomar
Thanks, but I need to get the text between <h1></h1> as in:"Lorem ipsum.", "The quick red fox..." etc. So not the text between H1 tags, but rather the text between an ending </h1> tag and a starting <h1>.
Francisc
@Francisc, I have updated the answer.
shamittomar
That's closer, thank you.I'll try to be more clear: I want to get the text between headings, count its length and decide if I want to hide part of it.You're answer is very helpful though. But what I want to do is keep all the text, just add a bit of html to hide part of it.
Francisc
Worked it out from your answer, thanks.
Francisc
A: 

If it something simple you can alwyas try PHP's function strip_tags

link: http://php.net/manual/en/function.strip-tags.php

It strips html tags from strings.

Tjorriemorrie
But the OP wants `text that's between the headings`. Pleas read the question carefully.
shamittomar
Yeah, thanks shamittomar.Tjorriemorrie: strip_tags wouldn't do the trick, and even if it did, it would strip any tags the text has as well, and I want to keep the formatting.
Francisc