PHP:如何通过字符限制内的单词和近换行符来断开字符串


PHP: How to break a string by words within a character limit and near line breaks

我正在使用一个糟糕的PDFLib包装器,它不能处理PDFLib对超过字符限制的单元格(每个单元格大约1600个字符)的问题。因此,我需要将一个大段落分成更小的字符串,这些字符串整齐地适合单元格,而不分解单词,并且尽可能靠近行尾。我对如何有效地做到这一点完全感到困惑(我需要它在合理的时间内运行)

这是我的代码,它仅根据字符长度将块切成子字符串,忽略了我上面提到的单词和行要求:

SPE_* 函数是包装类中的静态函数,SetNextCellStyle 调用用于在单元格轮廓周围绘制一个框需要 BeginRow 才能开始一行文本。结束一行文本需要 EndRow,必须在 BeginRow 之后调用它,如果预设的列数没有完全填充,则会生成错误。AddCell 将字符串添加到列数的第二个参数。

function SPE_divideText($string,$cols,$indent,$showBorders=false)
{
$strLim = 1500;
$index = 0;
$maxIndex = round((strlen($string) / 1500-.5));
$retArr= array();
  while(substr($string, $strLim -1500,$strLim)!=FALSE)
    {
    $retArr[$index] = substr($string, $strLim -1500,$strLim);
            $strLim+=1500;
            SPE_BeginRow();
            SPE_SetNextCellStyle('cell-padding', '0');
            if($indent>0)
              {
              SPE_Empty($indent);
              }
            if($showBorders)
              {
            SPE_SetNextCellStyle('border-left','1.5');
            SPE_SetNextCellStyle('border-right','1.5');
              if($index == 0)
                {
                SPE_SetNextCellStyle('border-top','1.5');
                }
                if($index== $maxIndex)
                  {
               SPE_SetNextCellStyle('border-bottom','1.5');
                  }
              }
            SPE_AddCell($retArr[$index],$cols-$indent);
            SPE_EndRow();
            $index++;
    }
}

提前感谢任何帮助!

这样的事情应该有效。

function substr_at_word_boundary($string, $chars = 100)
{
    preg_match('/^.{0,' . $chars. '}(?:.*?)'b/iu', $string, $matches);
    $new_string = $matches[0];
    return ($new_string === $string) ? $string : $new_string;
}
$string = substr_at_word_boundary($string, 1600)