Q: Display string to a maximum of so many characters without splitting word I am currently working on a php project where I need to display a string up to a maximum of 100 characters but without splitting the word. 
For example if I have the string

The quick brown fox jumped over the lazy dogs back

Say the 100th character is in the middle of 'jumped'. 
At the moment I am using substr($mystring, 0, 100)
This will then print 

The quick brown fox jum

Instead in this case I would want to print

The quick brown fox

Is this possible to fix

A: $string = 'The quick brown fox jumped over the lazy dogs back';
$maxLength = 20;

if (strlen($string) > $maxLength) {
    $stringCut = substr($string, 0, $maxLength);
    $string = substr($stringCut, 0, strrpos($stringCut, ' ')); 
}

echo $string;

// output: The quick brown fox

The key is using strrpos to cut off at a space rather than the middle of a word.
Note: If the source for these strings uses a multibyte charset, e.g., UTF-8, you will want to use the multibyte equivalent functions.

A: PHP's wordwrap() function can help.
http://php.net/manual/en/function.wordwrap.php
It's kinda hacky due to the separator string, but is concise:
$str2 = wordwrap($str,20,'@@@@@');
$str_final = substr($str2,0,strpos($str2,'@@@@@'));

Note that this will break if your original string contains '@@@@@', I'm using it as a unique separator that I figure will not be present in most english strings. Feel free to change '@@@@@' to something more wonky/unique.

A: //Set up -  we need 100 characters
$s="The quick brown fox jumped over the lazy dogs back";
$s="$s. $s. s.";

//Cut
$t=substr($s,0,100);

//Trim
$u=preg_replace('/^(.*).\s\w*$/','${1}',$t);

//Output
echo $u;

