Jump to content

Get Text between 1 group of Tags with PHP


Jumpy09

Recommended Posts

Alright so I am coding a site for a customer and I am currently in the News, wanting to show a list of the last 25 posts.  I am allowing direct HTML input as the Admin area is the only place to log-in and won't be accepting any content posted by their users.

 

So when the customer creates news, he must use <p></p> and <ul><li></li></ul> respectively to layout the news as he wants it to be.  The problem is I only really want to display the first 150 characters or so of the news topics in the News Listing.

 

I've googled this, and found a few methods but none of them really stick.

 

So what do I want to do?

Since the customer has to put paragraphs in <p></p> I want to take all the text out of the first paragraph, and the first paragraph only.  Then run it through substr and cut down the number of characters, then I will place it in <p></p> tags hard coded in.

 

So how do I get the content from inside the first <p></p> tag only and not all text from all the <p></p> tags?

 

Hopefully that is clear enough, I am a bit tired.

you can do it with preg_match, although I'm not very good at that, so here's a simple suggestion:

 

assuming you have a variable named $newsArticle that contains the entire article:

 

// split it where the </p> is
$parts = explode("</p>",$newsArticle);
// grab the wanted part and discard the rest. It will be index 0 since it's the first paragraph
$wantedPart = $parts[0];
unset($parts);
// remove the <p> tag from the start:
$finalText = str_replace("<p>","",$wantedPart);

 

Kind of an old-fashioned way to do it, but it should work.

 

Hope this helps

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.