Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/234.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 当达到某个字符限制时,是否将文本块修剪为最接近的单词?_Php_String - Fatal编程技术网

Php 当达到某个字符限制时,是否将文本块修剪为最接近的单词?

Php 当达到某个字符限制时,是否将文本块修剪为最接近的单词?,php,string,Php,String,问题是:当一定数量的字符已经过去时,您将如何将文本块修剪到最近的单词。我不是要限制某个单词或字母的数量,而是限制字母,并在最近的单词处将其截断 假设我有两条线: "This is a block of text, blah blah blah" "this is another block of txt 2 work with" 假设我想将其限制为27个字符,第一行将以“blah”结尾,第二行将以“txt”结尾,即使在这些单词中达到了字符限制 这个问题有没有干净的解决办法?使用占位符(即:##

问题是:当一定数量的字符已经过去时,您将如何将文本块修剪到最近的单词。我不是要限制某个单词或字母的数量,而是限制字母,并在最近的单词处将其截断

假设我有两条线:

"This is a block of text, blah blah blah"
"this is another block of txt 2 work with"
假设我想将其限制为27个字符,第一行将以“blah”结尾,第二行将以“txt”结尾,即使在这些单词中达到了字符限制


这个问题有没有干净的解决办法?

使用占位符(即:############),计算字符串的字符数减去您的占位符,用substr将其修剪到正确的长度,然后按占位符分解,不是更简单吗?

参见函数

我可能会这样做:

function wrap($string) {
  $wstring = explode("\n", wordwrap($string, 27, "\n") );
  return $wstring[0];
}

(如果您的字符串已经跨越了几行,请使用其他字符或模式来进行拆分,而不是“\n”)

我认为这应该可以做到:

function trimToWord($string, $length, $delimiter = '...')
{
    $string        = str_replace("\n","",$string);
    $string        = str_replace("\r","",$string);
    $string        = strip_tags($string);
    $currentLength = strlen($string);

    if($currentLength > $length)
    {
        preg_match('/(.{' . $length . '}.*?)\b/', $string, $matches);

        return rtrim($matches[1]) . $delimiter;
    }
    else 
    {
        return $string;
    }
}

您可以使用一个鲜为人知的修饰符str_word_count来帮助完成此操作。如果传递参数“2”,它将返回单词位置所在的数组

以下是使用此功能的简单方法,但可能更有效:

$str = 'This is a string with a few words in';
$limit = 20;
$ending = $limit;

$words = str_word_count($str, 2);

foreach($words as $pos=>$word) {
    if($pos+strlen($word)<$limit) {
        $ending=$pos+strlen($word);
    }
    else{
        break;
    }
}

echo substr($str, 0, $ending);
// outputs 'this is a string'
$str='这是一个包含几个单词的字符串';
$limit=20;
$ending=$limit;
$words=str\u word\u计数($str,2);
foreach($pos=>$word形式的单词){

if($pos+strlen($word)我写了一个函数,它可以做到这一点,而且非常干净。

chr(10)是一个比“\n”更好的解决方案,我相信。@Apikot-我认为任何东西都可以在这里工作,只要它不在字符串中-甚至像“[:CUT:]”这样的东西。为什么不删除else块并在if块之外返回$text呢?
// Trim very long text to 120 characters. Add an ellipsis if the text is trimmed.
if(strlen($very_long_text) > 120) {
  $matches = array();
  preg_match("/^(.{1,120})[\s]/i", $very_long_text, $matches);
  $trimmed_text = $matches[0]. '...';
}