Skip to content

Instantly share code, notes, and snippets.

@evgv
Last active February 22, 2018 13:43
Show Gist options
  • Save evgv/db0ffd1f6dd58c0c609ff3eb54ca0b0f to your computer and use it in GitHub Desktop.
Save evgv/db0ffd1f6dd58c0c609ff3eb54ca0b0f to your computer and use it in GitHub Desktop.
PHP. Code Snippet. Slice string by words.

Slice string by words

   /**
     * Slice string by words count and add `...` into the end
     * 
     * @param string $string
     * @param int $maxWords
     * @return string
     */
    public function sliceStringByWords($string, $wordsCount)
    {
        $words = explode(' ', $string);

        if (
            $wordsCount > 0 &&
            count($words) > $wordsCount
         ) {
            $string = rtrim(implode(' ', array_slice($words, 0, $wordsCount)), " !,.-") . '...';
        }

        return $string;
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment