PHP extract the first x characters of a text

This function extracts the first x characters of a given text, which we get from a database.
This is usually performed on posts on a blog, where you don’t want to display the whole post in the homepage, but just let’s say 500 characters of the post. Ok here is the function:

function extract($post_id, $length) {
	$sql = "SELECT id, LEFT(info, $length) as extraction FROM posts WHERE id = $post_id";
	$query = mysql_query($sql);

	while($row = mysql_fetch_array($query)) {		
		$extraction = $row['extraction'];
		$space = strrpos($extraction, ' ');		
		return substr($extraction, 0, $space);

$post_id is the id of the post in the database.
$length is the length of the extraction.

Then I’ve used the $space do get the position of the last occurence of a space (‘ ‘) in the $extraction.
This is needed to not return a text which is broken in half (for example “this pages address is klevismi”, instead of “this pages address is”).

This entry was posted in PHP/MySQL. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.