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 klevismiho.com”).

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

One Comment

  1. Jneinalsi
    Posted August 9, 2011 at 17:30 | Permalink

    Hi!
    Is there something interesting?

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>