How to only show the first x characters of a post as a preview (PHP)?
I was wondering how you would show only the first "x" char开发者_JAVA百科acters 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
Try:
preg_match('/^.{0,30}(?:.*?)\b/iu', $text, $matches);
which will match at most 30 chars, then break at the next nearest word-break
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
Use strpos()
with an offset to find a conveniently-placed space, and use substr()
to slice the string there.
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";
精彩评论