PHP在某些数量的字符之前在空格处拆分数组

时间:2017-03-16 10:25:18

标签: php

我的应用程序只能处理每行最多100个字符的文本。

但是我不想在句子中分割中间词,因为这看起来不太好。因此,我们需要在第100个字符之前找到空格,然后将其添加到数组中。

我在想使用strrpos会起作用 - 但我不确定如何继续这样做,所以它在一个数组中有所有内容

$textToDraw = 'this is a message that is over 100 characters long just to see how well that the breaks work';
$characterLimit = substr($textToDraw, 0, 100);
$textBeforeLimit = strrpos($characterLimit, ' ', 0);

由于

更新。这是我必须将文本拆分成数组然后绘制每一行的当前代码。但是我需要它在100个字符之前剪切空间 - 而不是在硬编码的100个字符限制上。

for ($i = 0; $i < count($textToDraw); $i++) {
    $splitPoint = 100;
    if ( strlen($textToDraw[$i]) > $splitPoint ) {
        $newTextLines = str_split($textToDraw[$i], $splitPoint);
        array_splice($textToDraw, $i, 1, $newTextLines);
        $i = $i + count($newTextLines) - 1;
    }
}
foreach ($textToDraw as $actualTextToDraw) {
    $page->drawText($actualTextToDraw, $this->x , $this->y , 'UTF-8');
}

2 个答案:

答案 0 :(得分:0)

尝试wordwrap()

使用字符串中断字符将字符串包含到给定数量的字符。

从文档页面改编的示例:

<?php
$text = "The quick brown fox jumped over the lazy dog.";
$newtext = wordwrap($text, 20, "<br />\n");

echo $newtext;

// Outputs:
// The quick brown fox<br />
// jumped over the lazy<br />
// dog.

有关新信息的更新:

将其应用于您的需求:

$text = "Here's some example text that may or may not be really really long.";
$linedText = wordwrap($text, 20, "\n");
$lines = explode("\n", $linedText);

// Do whatever with $lines.

答案 1 :(得分:0)

您可以使用php函数wordwrap,如下所示。这使用字符串中断字符将字符串包装到给定数量的字符。

<?php
$textToDraw = 'this is a message that is over 100 characters long just to see how well that the breaks work';

$newtext = wordwrap($textToDraw, 100, "<br />\n");

echo $newtext;
?>