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.

Link to comment
Share on other sites

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

Link to comment
Share on other sites

That is excellent, I have not actually gotten really use to the explode function yet.  Of course every once and a while something will slip right passed me, or I will forget something.

 

This actually will work really well, thank you very much.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.