Jump to content

Get preview of larger text.


speedy33417

Recommended Posts

I have larger diary entries that I'd like to a show a teaser version of with a "read more" link at the end.

I really suck with Regex. I just can't figure out the whole concept. Could some please help me with this?

 

I have $text variable holding the entire diary entry. How do I get a 100 character or larger teaser text out of it that ends with a comma or a dot? Obviously I don't want to just cut it at 100 characters.

 

Any help would appreciated!

Link to comment
https://forums.phpfreaks.com/topic/137134-get-preview-of-larger-text/
Share on other sites

Thanks. It's getting close to what I was looking for. First of all I changed it to $matches[0].

 

Other than that. Here's what I have:

 

	$text = "Thids asdhsdg shdgshdgh sd, sdsjhdjsd sdsdhs djshd sjdsd. Thsjdsjd sdjhs jdhsjdh sjd sdsd, sdjshdsj dhjsdhjshddd jsdh. Thsdjhsdjhsd shdjshdjshd jshd sjdhjshdjshdsd, sdhjsdhjs dhjshdjssd, sdhjshdjshdjsdsd, shdshdushdushdusd, sdhuisdhushdshdushd.";
$teaser = $text;
if(preg_match('/.{100}[^\s]*/',$teaser,$matches))
  $teaser = $matches[0];
echo $teaser; 

 

I get this result:

Thids asdhsdg shdgshdgh sd, sdsjhdjsd sdsdhs djshd sjdsd. Thsjdsjd sdjhs jdhsjdh sjd sdsd, sdjshdsj dhjsdhjshddd

 

It does not cut off the last word, but it does cut off the last sentence. I need the full sentence including the "dot".

 

Thanks.

Assigning $teaser to $text, only to pass $teaser through preg_match, and then assign $teaser to $matches[0] is jumping through extra hoops for nothing.

 

Here is my take on this (I have used the Lorem ipsum placeholder text, so that we can guage a little more accurately what is going on as far as how much preg_match grabs along the sentence).

 

$str = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer ut tellus. Cras nulla lacus, ultricies vel, scelerisque vel, sollicitudin non, eros. Nam id sapien nec elit fermentum dictum. Ut vitae enim.';

preg_match('#.{100}.*?[,.]#s', $str, $match);
echo $match[0];

 

Ouput:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer ut tellus. Cras nulla lacus, ultricies vel,

 

Is this along the lines of what you are looking for?

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.