• 0

[PHP] HTML Parsing


Question

I have a string that looks like this:

$String = "<H2>This is a header</H2>
<P>This is sample text. This is sample text. This is sample text. This is sample text. </P>

<P>This is even more sample text. This is even more sample text. Sample text is cool!</P>"

I'd like a small script to output the first 100 characters of the content of the first <P></P> tags. Can this be done? If so, please can someone post some example code?

Link to comment
Share on other sites

1 answer to this question

Recommended Posts

  • 0

I am almost positive there is a better way to remove the line feeds.. however this works for me in PHP5.

As a side note:

You might consider starting your variables with lowercase letters, many people associate names that start with a capital with objects. I suppose this situation is harder to come by in PHP as variables all start with $. :)

If you want to start following the XHTML standard, start using lowercase tag names as well. :)

&lt;?
$String = "&lt;H2&gt;This is a header&lt;/H2&gt;
&lt;P&gt;This is sample text. This is sample text. This is sample text. This is sample text. &lt;/P&gt;
&lt;P&gt;This is even more sample text. This is even more sample text. Sample text is cool!&lt;/P&gt;";
$tmpstr = str_replace("\r", "", $String);
$tmpstr = str_replace("\n", "", $tmpstr);
preg_match("/^&lt;h2&gt;.*?&lt;\/h2&gt;&lt;p&gt;(.*?)&lt;\/p&gt;/i", $tmpstr, $matches);
print substr($matches[1], 0, 100);

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.