PHP处理小说章节并分割成文件
先缕清思路,
拿到一个超大TXT小说之后能干什么、是不是得按照章节给逐个分清各个小文件
思路是用正则匹配每个章节,把内容里的章节全给匹配到,再放到数组遍历用explode给逐个分割,每一章对应生成每一章的文件。
<?php
$dir="./static/book/".base64_encode($bookname);//上传路径
if(!file_exists($dir))
{
mkdir($dir,0777,true);
}
$file_name='./static/book/'.$newName;//要分割的文件
$str=file_get_contents($file_name);
$str=mb_convert_encoding($str,"UTF-8","GBK");
$arr=[];
if(preg_match_all("/(\x{7b2c})(\s*)([\x{96f6}\x{4e00}\x{4e8c}\x{4e09}\x{56db}\x{4e94}\x{516d}\x{4e03}\x{516b}\x{4e5d}\x{5341}\x{767e}\x{5343}0-9]+)(\s*)([\x{7ae0}\x{8282}]+)/u",$str,$matches))
{
$matches=array_slice($matches[0], 0,count($matches[0]));
for ($i=0; $i <count($matches); $i++)
{
$j=$i+1;
if(isset($matches[$j]))
{
$pattern="#$matches[$i](.*)$matches[$j]#isU";
$arr[$i]=$pattern;
}
else
{
$offset=count($arr);
$arr[$offset]="#$matches[$i](.*)[\w]#isU";
}
}
}
$arr=array_unique($arr);
foreach ($arr as $key => $value)
{
preg_match($value, $str,$arr[$key]);
unset($arr[$key][0]);
}
var_dump($arr);
宠物免费领养小程序,欢迎来踩