1

So, beginner designer here so any help given will be much appreciated and rewarded with internet cookies.

I have dynamic content for a news site that grabs its' stories from a daily updated database. We are redesigning and it's always been a pet peev of mine that the whole teaser is put into the front page. I'm condensing it down and modified a substr that was suggested to me.

<?php

        $position=200;

        $post = substr($row_News['teaser'],0,$position);

        echo $post;
        echo "...";
        ?>

It works absolutely perfect, expect for the fact it cuts a word in half. Since the teasers are always changing, is this fixable or just something i have to live with if I use this substr?

Thanks always, cookies to be given out shortly.

  • 1
    I would suggest looking at the answers here: http://stackoverflow.com/questions/1233290/making-sure-php-substr-finishes-on-a-word-not-a-character/1233360#1233360 – JWMarchant Oct 22 '13 at 14:44
  • Possible duplicate of [How to Truncate a string in PHP to the word closest to a certain number of characters?](http://stackoverflow.com/questions/79960/) – Amal Murali Oct 22 '13 at 14:48
  • It is similar and probably a dup, but I have tried for about an hour with working with them, so I thought to just ask and see if I was missing something, which i was. – user2907544 Oct 22 '13 at 14:57

3 Answers3

0

Question is almost the same as Making sure PHP substr finishes on a word not a character

Example:

$post = $row_News['teaser'];
if (preg_match('/^.{1,260}\b/s', $row_News['teaser'], $match))
{
    $post=$match[0];
}
Community
  • 1
  • 1
Sjerdo
  • 187
  • 1
  • 4
0

This is the way to do without using regex :

<?
$position=200;
$post = substr($row_News['teaser'],0,$position);
$post = substr($post, 0, strrpos($post, ' '));
echo $post."....";
?>

Reference : Making sure PHP substr finishes on a word not a character

Community
  • 1
  • 1
Subin
  • 3,445
  • 1
  • 34
  • 63
  • Internet cookies for all, but two for you! Tried them all and modified as needed to get to work, and this one is what i was most looking for. Thanks! – user2907544 Oct 22 '13 at 15:06
0

you need wordwrap() function

$string_limit = 200;
$delimiter = "...";
if(strlen($row_News['teaser']) > $string_limit){

    // If string is bigger than limit
    $intact = wordwrap($row_News['teaser'], $string_limit);
    $intact_array = explode("\n", $intact);
    $str = $intact_array[0] . $delimiter;
}
else{

    // else string will be as it is
    $str = $row_News['teaser'];
}
Bhavik Shah
  • 2,300
  • 1
  • 17
  • 32