westman Posted December 14, 2012 Share Posted December 14, 2012 hi there am trying to print out a string and if the string is more then 20 then the end will be cut and replaced with "..."this is what i have so fare $name = substr ($name, 0, 20);i can cut any string to 20 no prob but how do i add "..." at the end if the string is more than 20? Link to comment Share on other sites More sharing options...
Ingolme Posted December 14, 2012 Share Posted December 14, 2012 Check strlen(). $e = '';if(strlen($str) > 20) { $e = '...';}$output = substr($str, 0, 20);$output .= $e; Link to comment Share on other sites More sharing options...
westman Posted December 14, 2012 Author Share Posted December 14, 2012 thank you so much it works well Link to comment Share on other sites More sharing options...
birbal Posted December 14, 2012 Share Posted December 14, 2012 ..also you can do like $output = str_pad(substr($str, 0, 20),23,'...',STR_PAD_RIGHT); http//php.net/str_pad If you are doing this for visual cliping of textual content. there is CSS option for that http://w3schools.com/cssref/css3_pr_text-overflow.asp Link to comment Share on other sites More sharing options...
justsomeguy Posted December 14, 2012 Share Posted December 14, 2012 Here's a version that supports UTF characters: function str_maxwidth($str, $w){ return (mb_strlen($str, 'UTF-8') <= $w ? $str : (substr_unicode($str, 0, $w - 3) . '...'));}function substr_unicode($str, $s, $l = null){ // stolen from the php.net manual page for mb_substr return join("", array_slice(preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY), $s, $l));} Call str_maxwidth with the string and maximum length. Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now