Edward Posted September 15, 2008 Share Posted September 15, 2008 Hi, I am using the following code to display a preview of a long variable, like so: if ((strlen($blog_article)) > 100) { $blog_article_preview = substr($blog_article,0,97).'...'; } However, I don't want the preview value to end during a word. Is there a way to limit the characters at the most recent space? i.e. 'Welcome to my new websi...' would become 'welcome to my new'. Thanks in advance. Quote Link to comment https://forums.phpfreaks.com/topic/124384-substr-to-limit-characters-rounding-to-nearest-space/ Share on other sites More sharing options...
BlueSkyIS Posted September 15, 2008 Share Posted September 15, 2008 what i use, where $acc_desc is the original string and $blurb is the result string: $blurb_len = 320; // max number of characters allowed in the blurb $blurb = ""; $ed_parts = explode(" ",$acc_desc); foreach ($ed_parts AS $a_word) { // Leave if this word breaks our strlen limit if (strlen($blurb . " $a_word") > $blurb_len) { break; } $blurb .= "$a_word "; } // if no period on the end, add ellipsis $blurb = trim($blurb); if (substr($blurb, -1, 1) != '.') { $blurb .= " ..."; } Quote Link to comment https://forums.phpfreaks.com/topic/124384-substr-to-limit-characters-rounding-to-nearest-space/#findComment-642366 Share on other sites More sharing options...
Edward Posted September 15, 2008 Author Share Posted September 15, 2008 Hi, That seems to be working great, thanks! I did actually make two minor amendments, which I think change it to how I wanted it. Perhaps you could check that what I've done is ok?? $blurb = ""; $blurb_len = 97; // max number of characters allowed in the blurb $ed_parts = explode(" ",$acc_desc); foreach ($ed_parts AS $a_word) { // Leave if this word breaks our strlen limit if (strlen($blurb . "$a_word") > $blurb_len) { // I REMOVED THE SPACE BEFORE $a_word SO THAT A WORD WITH n AMOUNT OF CHARACTERS WILL FIT IN A GAP OF n CHARACTERS break; } $blurb .= "$a_word "; } // if no period on the end, add ellipsis $blurb = trim($blurb); if (substr($blurb, -1, 1) != '.') { $blurb .= "..."; // I REMOVED THE SPACE BEFORE THE ELLIPSES } Thanks again! Quote Link to comment https://forums.phpfreaks.com/topic/124384-substr-to-limit-characters-rounding-to-nearest-space/#findComment-642374 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.