PHP:在多个字符块中剪切字符串

时间:2012-05-31 11:18:19

标签: php count split character

我有一个名为$ data的变量,其中包含一个巨大的字符串(27338个字符)。

此字符串将是pdf文件的内容。

我需要在pdf文件的每一页末尾添加一个脚注。

我每页计算了2642个字符。

如何在2642个字符的块中剪切$ data,以便添加脚注?

我正在尝试:

$split = preg_split('/(.{0,2642})\s/',
                    $data,
                    0,
                    PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

$count = count($split);
foreach ($split as $key => $page) {

    echo $page; echo "<br><br>";
}

但是每个$页面显示的字符少于2642个字符。

非常感谢

3 个答案:

答案 0 :(得分:2)

我从未在非常大量的数据中使用它,但是在相同长度的元素中拆分字符串的方法是使用str_split函数(参见http://php.net/str_split

用法:

$array = str_split('some text', 2);

你会得到一个长度为2的元素的数组(除了最后一个)

答案 1 :(得分:0)

您可以使用substring-function,它将从不同的字符串创建特定的子字符串(定义的长度)。

substr($STRING, A, B); //where $string is the original string, 
                       //A is the position where to start cutting
                       //B is how long the newly created string should be (it's optional!)
$text = "ABCDEF";
echo substr($text, 2, 2); //will give you "CD"

答案 2 :(得分:0)

此?

define("CHUNK_SIZE",2642);
$string = "big..";
$chunks = array();
for($x=0,$sz=strlen($string);$x<$sz;$x+=CHUNK_SIZE) {
   $chunks[] = substr($string,$x,$x+CHUNK_SIZE);
}
$chunks[0..n] += FOOTNOTE

然后:

implode("",$chunks);