1

I want to use part of a blog post as the introduction to the post and then add a "read more" link at the end, but I couldn't find a way to round up the text either at the end of a word or sentence. The code below runs into an empty infinite loop.

<?php

$num_of_words = 400;
while (! substr($article, $num_of_words, 1) != "")
     $num_of_words++;

?>

Any help please? Thanks

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Chibuzo
  • 6,112
  • 3
  • 29
  • 51
  • 1
    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/how-to-truncate-a-string-in-php-to-the-word-closest-to-a-certain-number-of-charac) – Felix Kling Feb 01 '11 at 14:58
  • "If not substring is not something".. Double negation?! Having readable code must be really low-priority in your code – ThiefMaster Feb 01 '11 at 15:18
  • I never thought of that. Thanks for pointing it out. – Chibuzo Feb 02 '11 at 18:48

4 Answers4

1

Another way to do it would be something like this:

if (strlen($article) <= 400)
    $intro = $article;
else
    $intro = substr($article, 0, strrpos($article, ' ', strlen($article)-400));
MarioVW
  • 2,225
  • 3
  • 22
  • 28
0

You can use regular expressions, if you want to get the first 25 words you could use something like

^([\w,\.:;]+\s+){1,25}

If you need more help with regular expressions just ask...

MarioVW
  • 2,225
  • 3
  • 22
  • 28
0
<?php

$num_of_words = 400;

$art=explode(' ',$article);
$shortened='';
for ($i=0 ; $i<=$num_of_words ; $i++){
    $shortened.=$art[$i].' ';
}
echo $shortened;
?>

this will print out the first 400 WORDS ...

Rami Dabain
  • 4,709
  • 12
  • 62
  • 106
0

Assuming that there is a max length you don't want to exceed even if there is no whitespace, something like this would work:

$maxlength=100; //100 characters
$mystring='I want to use part of a blog post as the introduction to the post and then add a "read more" link at the end, but I couldn't find a way to round up the text either at the end of a word or sentence. The code below runs into an empty infinite loop.';

$mystring=substr($mystring,0,$maxlength); //now string can't be too long
$last_space=strrpos($mystring,' ');
$mystring=substr($mystring,-,$last_space);

But if you really want to do it by word count, keeping in mind that words can be very long, a regex like this should match up to the 1st 25 words.

/^(\w+\b){1,25}/
dnagirl
  • 20,196
  • 13
  • 80
  • 123