$charger是一个字符串,用于存储一本书中包含10000-15000个字符的章节。我想把字符串分成至少有1000个字符的段,但在下一个空格之后正式断开,这样我就不会断开一个单词。提供的代码将成功运行约9次,然后会遇到运行时问题。
"致命错误:第16行D:''htdocs''test.php中超过了30秒的最长执行时间"
<?php
$chapter = ("10000 characters")
$len = strlen($chapter);
$i=0;
do{$key="a";
for($k=1000;($key != " ") && ($i <= $len); $k = $k+1) {
$j=$i+$k; echo $j;
$key = substr($chapter,$j,1);
}
$segment = substr ($chapter,$i,$k);
$i=$j;
echo ($segment);
} while($i <= $len);
?>
我认为编写它的方法开销太大,虽然增加max_execution_time会有所帮助,但并不是每个人都能修改自己的服务器设置。这个简单的事情将15000字节的lorum ipsum文本(2k个单词)拆分为1000个字符段。我认为它会做得更好,因为执行时间相当快。
//Define variables, Set $x as int(1 = true) to start
$chapter = ("15000 bytes of Lorum Ipsum Here");
$sections = array();
$x = 1;
//Start Splitting
while( $x ) {
//Get current length of $chapter
$len = strlen($chapter);
//If $chapter is longer than 1000 characters
if( $len > 1000 ) {
//Get Position of last space character before 1000
$x = strrpos( substr( $chapter, 0, 1000), " ");
//If $x is not FALSE - Found last space
if( $x ) {
//Add to $sections array, assign remainder to $chapter again
$sections[] = substr( $chapter, 0, $x );
$chapter = substr( $chapter, $x );
//If $x is FALSE - No space in string
} else {
//Add last segment to $sections for debugging
//Last segment will not have a space. Break loop.
$sections[] = $chapter;
break;
}
//If remaining $chapter is not longer than 1000, simply add to array and break.
} else {
$sections[] = $chapter;
break;
}
}
print_r($sections);
编辑:
在几分之一秒内测试了5k个单词(33K字节)。把课文分成33段。(哎呀,我以前把它设置成了10万个字符段。)
在代码中添加了详细的注释,以解释一切的作用。
这里有一个简单的函数来完成
$chapter = "Your full chapter";
breakChapter($chapter,1000);
function breakChapter($chapter,$size){
do{
if(strlen($chapter)<$size){
$segment=$chapter;
$chapter='';
}else{
$pos=strpos($chapter,' ', $size);
if ($pos==false){
$segment=$chapter;
$chapter='';
}else{
$segment=substr($chapter,0,$pos);
$chapter=substr($chapter,$pos+1);
}
}
echo $segment. "'n";
}while ($chapter!='');
}
检查每个字符不是一个好的选择,而且是资源/时间密集型
附言:我还没有测试过(只是在这里输入),这可能不是最好的方法。但逻辑是可行的!
您总是从一开始就阅读$章节。你应该从$charger中删除已经阅读的字符,这样你就永远不会阅读超过10000个字符。如果你这样做,你还必须调整周期。
尝试
set_time_limit(240);
在代码的开头。(这是ThrowSomeHardwareAtIt通道)
只需一行即可完成,大大加快了代码的编写速度。
echo $segment = substr($chapter, 0, strpos($chapter, " ", 1000));
它将使用本章的子字符串直到1000+一些字符直到第一个空格。