Wednesday 29 October 2014

Show First 3/n Words From A String Value In PHP

Below code will explain how to do this in detail.

<?php

function showStripString ($num,$myString,$maxNumOfWords) {
    if($num>0) {
        if($num<=$maxNumOfWords) {
            $spaceChar = '/\S*';
            for($i=1;$i<$num;$i++) {
                $spaceChar .= '\s\S*';
            }
            $spaceChar .='/';
            preg_match("$spaceChar", $myString, $result);
            return $result[0];
        }else return "ERROR !!! Number of words exceeded the actaul number of words in you string ($myString)";
    }   
    else return "ERROR !!";
   
}
//your string
$str = "i want to buy a new car";
//Number of words you want to show
$number=3;

//remove whitespace from beginning and end of string
$str = trim($str);
//get number of whitespace
$nuberOfWhiteSpace = substr_count($str, ' ');
//Get Total number of words
$TotalNumberOfWords = $nuberOfWhiteSpace + 1;

//call function
echo showStripString(intval($number),$str,$TotalNumberOfWords);

?>