I have the following code for outputting some text retrieved from my database:
<p><?php echo nl2br(bb_code($bodytext)); ?></p>
What I'd like to do is add a "sneak preview" where only the first 250 characters or so are displayed, and then the user can click a link to read the whole thing. Something like this:
<p><?php echo nl2br(bb_code(substr($bodytext, 0, 250))); ?>...<br />
<a href="#">Continue reading</a></p>
There are obviously several problems here.
[url=http://www..example.com]link[/url]
would be interpreted as 39 characters when it should be interpreted as 4.How can I accomplish this?
Preview text (sometimes referred to as "preheader text") is a brief description of what's in your email, shown as a preview in the inbox of most major email clients next to the subject line. It's a good idea to include preview text as it captures your audiences' attention and generally leads to higher open rates.
Preview text is the bit of text below or next to an email's subject line in the inbox and gives extra insight into what's inside the email. Gmail refers to this as Snippets, Apple Mail refers to it as a preview, and Outlook calls it a Message Preview. No matter what it's called, this copy is the preview text.
When testing with bbCode Playground I noticed that bbCode doesn't appear to allow escapes, and will return bracketed text as long as it didn't match any of the codes and formats specifically. You run the risk of incorrectly replacing text in brackets with a generic approach.
The following code will replace the bbCode, looking for specific tags. It does not check for attributes, only if a tag allows attributes or not. Also it will still incorrectly match things that bbCode will not such as [b]asdasd[b]asdsda[/b]dasd[/b]
in bbCode would return asdasd[b]asdsdadasd[/b]
and this will return asdasdasdsdadasd
. If you need something more accurate, you need a parser.
<?php
function createPreview($text, $limit) {
$text = preg_replace('/\[\/?(?:b|i|u|s|center|quote|url|ul|ol|list|li|\*|code|table|tr|th|td|youtube|gvideo|(?:(?:size|color|quote|name|url|img)[^\]]*))\]/', '', $text);
if (strlen($text) > $limit) return substr($text, 0, $limit) . "...";
return $text;
}
?>
<p><?php echo nl2br(createPreview($bodytext)); ?></p>
I noticed in the other answer they are looking for exclamation points. I don't know the significance of those in bbCode. You can add it at the start '/\[[\/!]?...
if it is signficant.
The below fiddle shows how it works with some example text.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With