tags:

views:

76

answers:

4

I was wondering how you would show only the first "x" characters of a post, as a preview. Sort of like what StackOverflow does when they show there list of questions.

The quick brown fox jumps over the lazy dog

goes to

The quick brown fox jumps...

I dont want to split up a word in the middle. I was thinking the explode function splitting up at every space , explode(" ", $post), but I wasnt too sure if there was another way or not. Thanks

+1  A: 

Use strpos() with an offset to find a conveniently-placed space, and use substr() to slice the string there.

Ignacio Vazquez-Abrams
+8  A: 

Try:

preg_match('/^.{0,30}(?:.*?)\b/iu', $text, $matches);

which will match at most 30 chars, then break at the next nearest word-break

K Prime
+1: Nice one, fixed typo.
Alix Axel
Fixed some more stuff.
Alix Axel
@Alix - actually on second thoughts, you wouldn't need the grouping at all - `$matches[0]` would be correct no?
K Prime
Yeah, right! Sorry...
Alix Axel
+1  A: 

you can try wordwrap

$str = "The quick brown fox jumps over the lazy dog";
$x = 14;
$newtext = wordwrap($str, $x);
$s  = explode("\n",$newtext,2);
print $s[0];

NB: if $x is say 8, the output will be "The" , not "The quick"

You can also use explode.

$str = "The quick brown fox jumps over the lazy dog";
$s = explode(" ",$str);
$x=14;
$final="";
foreach ($s as $k){
    if ( strlen($final) <= $x ){
        $final.="$k ";
    }else{ break; }
}
print "-> $final\n";
ghostdog74
A: 

strpos ( http://www.php.net/strpos ) will give you what you need. This function should give you what you need.

function getPreview($text, $minimumLength=60){
     return substr($text,0,strpos($text,' ',$minimumLength)) . '...';
}

Note: I haven't tested that function

Warren Krewenki