简体   繁体   中英

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

$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, eg, UTF-8, you will want to use the multibyte equivalent functions.

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.

//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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM