PHP trim_better() function

Every developer has a set of utility functions that are added to every project, tools that enhance the built-in capabilities of a language. Today, we look at a PHP function in my utilities, trim_better(), a tool that builds on PHP's existing trim() and substr() functions.

With trim_better(), you can shorten a string to a maximum length, but without splitting in the middle of a word. You can also, optionally, strip HTML tags and append ellipses (...).

I originally found this snippet from Elliott Brueggeman, but added a few bug fixes and enhancements. Enjoy!

Subscribe to 90 Degrees

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe