简体   繁体   English

显示字符串最多不超过单词个数

[英]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. 我目前正在处理一个php项目,该项目需要显示最多100个字符的字符串,但不拆分单词。

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'. 假设第100个字符位于“跳”的中间。 At the moment I am using substr($mystring, 0, 100) 目前我正在使用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. 关键是使用strrpos切断空格而不是单词的中间。

Note: If the source for these strings uses a multibyte charset, eg, UTF-8, you will want to use the multibyte equivalent functions. 注意:如果这些字符串的源使用多字节字符集,例如UTF-8,则需要使用多字节等效功能。

PHP's wordwrap() function can help. PHP的wordwrap()函数可以提供帮助。 http://php.net/manual/en/function.wordwrap.php 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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