Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to only show the first x characters of a post as a preview (PHP)?

Tags:

function

php

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

like image 400
BDuelz Avatar asked Dec 14 '22 00:12

BDuelz


2 Answers

Try:

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

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

like image 74
K Prime Avatar answered Feb 23 '23 00:02

K Prime


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

like image 22
Warren Krewenki Avatar answered Feb 23 '23 00:02

Warren Krewenki