Web Niraj
  • Facebook
  • Flickr
  • Github
  • Linkedin
  • Twitter
  • YouTube
Online portfolio, code examples and developer blog
  • About
  • Contact
  • Portfolio
  • WordPress
Search the site...
  • Home
  • Blog
  • PHP Substring – Respecting the Last Word

PHP Substring – Respecting the Last Word

0

Sometimes, you want to truncate a string to a given length, but keep the last word of the string intact. For example, reducing the string “Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt” to 35 characters, but we don’t want any word to be cut-off.

The following function does exactly that…

function substr_word( $string, $len = 35 ) {
    return substr( ( $str = wordwrap( $string, $len, '$$' ) ), 0, strpos( $str, '$$' ) );
}

This function would reduce the above string to “Lorem ipsum dolor sit amet,”. The word “consectetur” falls in the cut off point, but instead of cutting off the word, the string is reduced to the end of the previous word.

Function, PHP

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

StackExchange / StackOverflow

profile for Niraj Shah on Stack Exchange, a network of free, community-driven Q&A sites

PSN Profile

Tags

Amazon Web Services Android Android 4.4 KitKat Android 5.0 Lollipop Apache API Application Backup Bug Command Line Cordova Example Facebook Facebook Graph API Facebook PHP SDK 4.0 Facebook Social Plugins Fan Page Flash Geolocation Google Nexus 5 Google Nexus One Hacking HTML5 Image Manipulation iOS iPhone JavaScript jQuery Laravel 5 Linux NodeJS Parse PDF PHP Plugin Portfolio Review Security Server SSH SSL Sysadmin Tutorial WordPress WordPress Plugins
© 2011-2021 Niraj Shah
  • Blog
  • Portfolio
  • WordPress
  • About Me
  • Contact Me
  • Privacy Policy