Monday, 2 February 2015

First Words

First Words

If you have ever need to grab the first few words of a string, then this simple function allows you to specify exactly how many words you want and even has a tail that defaults to three dots. This, of course, can be changed to a read more link or anything you like. Enjoy!

<?php
/***
 * @snarf the first n words from a string
 *
 * @param string $string
 *
 * @param int $num
 *
 * @param string $tail
 *
 * @return string
 */
function first_words($string$num$tail='&nbsp;...')
{
        
/** words into an array **/
        
$words str_word_count($string2);

        
/*** get the first $num words ***/
        
$firstwords array_slice$words0$num);

        
/** return words in a string **/
        
return  implode(' '$firstwords).$tail;
}

 
/*** a string ***/
 
$string 'Heather was hoping to hop to Tahiti to hack a hibiscus to hang on her hat';

 
/*** get the first 5 words ***/
 
echo first_words$string5);
?>
The output from the above script will look like this:
Heather was hoping to hop ...
I have recieved many requests from PHPRO.ORG regulars for a method of achieving this same result when SELECTing from a MySQL database, rather than SELECT a whole bunch of text and then drag it into PHP as a variable and then manipulate it. So lets imagine we have a table named animals with three fields, animal_id, animal_name, and animal_description. The animal_description field is a LARGETEXT field and we wish only to snarf the first fifteen words. Our SQL query would look like this:
SELECT
animal_id,
animal_name,
SUBSTRING_INDEX(animal_description,' ', 15) AS first_fifteen
FROM animals

0 comments:

Post a Comment