Limit String Characters Without Cutting Them in PHP

This function is an alternative to substr. The function substr can cut your words in half so this function works great in order to prevent cutting words in half.

I have always user substr, but it become annoying when it cuts strings or words in the middle. I used to use substr for small blog description before getting to the full blog post. This function has saved me. This does not cut your string in half. 

Use this in your projects. I love this function i call it stringTruncate()

function stringTruncate($string, $your_desired_width) {
	$parts = preg_split('/([snr]+)/', $string, null, PREG_SPLIT_DELIM_CAPTURE);
	$parts_count = count($parts);

	$length = 0;
	$last_part = 0;
	for (; $last_part < $parts_count; ++$last_part) {
		$length += strlen($parts[$last_part]);
		if ($length > $your_desired_width) { break; }
	}

	return implode(array_slice($parts, 0, $last_part));
}

How to Use: 

<?php echo stringTruncate($string, 500); ?>

 

Enjoy!!