Search code examples
phparraysstringword-count

PHP Word Count Function


I am attempting to write my first custom function. I understand that there are other functions out there that do the same thing that this does, but this one is mine. I have the function wrote, but I do not understand char_list as it pertains to functions and cannot figure out the third parameter of the str_word_count function in php. I think I need to this in a certain format to maintain periods, comma, semi-colons, colons, etc. Please note that double and single quotes are maintained throughout the function. It is bottom symbols that are strip from the string.

$text = "Lorem ipsum' dolor sit amet, consectetur; adipiscing elit. Mauris in diam vitae ex imperdiet fermentum vitae ac orci. In malesuada."

function textTrim($text, $count){ 
  $originalTxtArry = str_word_count($text, 1);

  $shortenTxtArray = str_word_count(substr(text, 0,$count), 1);
  foreach ($shortenTxtArray as $i=>$val) {
    if ($originalTxtArry[$i] != $val) {
      unset($shortenTxtArray[$i]);
    }
  }
  $shortenTxt = implode(" ", $shortenTxtArray)."...";
  return $shortenTxt;
} 

Output Lorem ipsum' dolor sit amet consectetur adipiscing elit Mauris in diam...

Notice the "," after amet is missing.

Ignore the string of periods at the end, I concatenate those on to the end before the return

Thank You for all assistance.

Dave


Solution

  • Updated function to explode based on a space

    function textTrim($str, $limit){ 
        /** remove consecutive spaces and replace with one **/
        $str = preg_replace('/\s+/', ' ', $str);
    
        /** explode on a space **/
        $words = explode(' ', $str);
    
        /** check to see if there are more words than the limit **/
        if (sizeOf($words) > $limit) {
            /** more words, then only return on the limit and add 3 dots **/
            $shortenTxt = implode(' ', array_slice($words, 0, $limit)) . '...';
        } else {
            /** less than the limit, just return the whole thing back **/
            $shortenTxt = implode(' ', $words);
        }
        return $shortenTxt;
    }