PHP Freelancer Developer from India
PHP
How find first few words of the given Text/String using php
Nov 17th
To find first few words please use any one of the following function:
Function 1.
<?php
function first_words($string, $num, $tail=’ …’)
{
/** words into an array **/
$words = str_word_count($string, 2);
/*** get the first $num words ***/
$firstwords = array_slice( $words, 0, $num);
/** return words in a string **/
return implode(‘ ‘, $firstwords).$tail;
}
/*** a string ***/
$string = ‘Heather was hoping to hopqq to Tahiti to hack a hibiscus to hang on her hat’;
/*** get the first 5 words ***/
echo first_words( $string, 5);
?>
Function 2.
<?php
function first_few_words($text,$limit=20){
$explode = explode(‘ ‘,$text);
$string = ”;
$dots = ‘…’;
if(count($explode) <= $limit){
$dots = ”;
}
for($i=0;$i<$limit;$i++){
$string .= $explode[$i].” “;
}
if ($dots) {
$string = substr($string, 0, strlen($string));
}
$string = ‘Heather was hoping to hopqq to Tahiti to hack a hibiscus to hang on her hat’;
return $string.$dots;
}
echo first_few_words( $string, 5);
?>
Recent Comments