$ chapter是一个字符串,用于存储10,000到15,000个字符的书籍章节。我想将字符串分解成至少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);
?>
答案 0 :(得分:1)
我认为你编写它的方法有太多的开销,而增加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个部分。 (哎呀,我以前把它分成了10K字符段。)
为代码添加了详细的注释,以解释所有内容的作用。
答案 1 :(得分:0)
你总是从一开始就阅读$章节。您应该从$ chapter中删除已读取的字符,这样您将永远不会读取超过10000个字符。如果你这样做,你还必须调整周期。
答案 2 :(得分:0)
试
set_time_limit(240);
在代码的开头。 (这是ThrowSomeHardwareAtIt方法)
答案 3 :(得分:0)
它可以在一行中完成,这会大大加快您的代码。
echo $segment = substr($chapter, 0, strpos($chapter, " ", 1000));
直到第一个空格,它才会占据章节的子串直到1000 +一些字符。
答案 4 :(得分:0)
这是一个简单的功能
$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!='');
}
检查每个字符不是一个好的选择,并且是资源/时间密集型的
PS:我没有测试过这个(只是输入这里),这可能不是最好的方法。但逻辑有效!