Truncating or trimming the length of a string down to a set limit is a task that we do often. Right? You have a blog page and you want to show a snippet of the content, but only 200 or 300 words and not the whole 2000 word articles.
WordPress has a function built in that you can use called
wp_trim_words(). I have one that I’ve used which is inspired by Laravel and Symfony. It’s part of my Fulcrum plugin that I use on all of my projects. Genesis has one built into too called
genesis_truncate_phrase(). There are multiple ways to trim and truncate long strings to a set number of words.
In this episode, let’s explore the one I use and then compare it to
Your best friend is code, Tonya is making the introductions.
Total Lab Runtime: 01:58:54
- 1 Lab Introductionfree 03:24
- 2 Checking if String Starts With a Character or Substringpro 13:43
- 3 Explaining the "String Starts With" Strategypro 13:35
- 4 Check if String Ends With a Character or Substring - Part 1pro 15:11
- 5 Check if String Ends With a Character or Substring - Part 2pro 12:52
- 6 Has Substringpro 04:27
- 7 Truncate by Characterspro 17:18
- 8 Truncate by Wordspro 14:35
- 9 Converting to Lowercasepro 07:58
- 10 Converting to Uppercasepro 01:30
- 11 Splitting a String into An Arraypro 07:17
- 12 Joining Array Elements into a Stringpro 03:43
- 13 Wrap it Uppro 03:21