Jump to content

substr to limit characters, rounding to nearest space?


Edward

Recommended Posts

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.

 

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 .= " ...";
}

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!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.