• Sign in to Neowin Faster!

    Create an account on Neowin to contribute and support the site.

  • 0
Sign in to follow this  

[PHP] HTML Parsing

Question

AshMan    0

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?

Share this post


Link to post
Share on other sites

1 answer to this question

Recommended Posts

  • 0
PKHelloNasty    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);

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.