为保证精确拆分,txt必须符合下图格式,且文件名就是小说名(采集软件可采集生成此种txt)
导入后的效果
// 导入整本
public function importtxt(){
set_time_limit(0);
try {
$file=request()->file('txt');
} catch (\Exception $e) {
return errorjson(300,$e->getMessage());
}
if(!$file){
return errorjson(301,'上传失败');
}
$txt=$file->getOriginalName();
// 获取书名
$name = trim(explode('.', basename($txt), 2)[0]);
$content=file_get_contents($file->getRealPath());
// 获取 第一个章节前的图书信息,作者、分类、图片、简介
$pos=mb_strpos($content,"【【");
$metainfo=$pos<=0?'':mb_substr($content,0,$pos);
// 移除第一个章节前的基础信息
if(mb_strlen($metainfo)>0){
$content=mb_substr($content,$pos);
}
// 如果不存在图书,则获取基本信息后插入codeit.org.cn
$book_id = Db::name('books')->where('name', $name)->value('id');
if (!$book_id) {
$cid=1;
preg_match("/作者.\s*?(\S+)\s*?/",$metainfo,$zuozhe);
preg_match("/图片.*?(http.*\.(?:jpg|png|jpeg))\s*?/",$metainfo,$tupian);
preg_match("/简介.\s*?(.+)/",$metainfo,$jianjie);
preg_match("/(?:分类|类别).\s*?(.+)/",$metainfo,$fenlei);
$fenlei=isset($fenlei[1])?str_replace('小说','',$fenlei[1]):"";
if($fenlei){
// 搜索是否有相同的分类
$cids=(int)Db::name('categorys')->where('name','like','%'.$fenlei.'%')->value('id');
if($cids<1){
$cids=(int)Db::name('categorys')->where('name','like','%'.mb_substr($fenlei,0,2).'%')->value('id');
}
// if($cids>0){
$cid=$cids>0?$cids:$cid;
// }
}
$book_id=Db::name('books')->insertGetId([
"name"=>$name,
"author"=>isset($zuozhe[1])?$zuozhe[1]:"",
"pic"=>isset($tupian[1])?$tupian[1]:"",
"summary"=>isset($jianjie[1])?$jianjie[1]:"",
"c_name"=>'',
"cid"=>$cid??1,
"length"=>0
]);
if($book_id<1){
return errorjson(227,"出错了");
}
}
$txtpath=app()->getRootPath()."runtime/txt/{$book_id}/";
if(!is_dir($txtpath)){
mkdir($txtpath,0777);
}
$content=trim($content);
$contentarr=preg_split("/【【.*?】】/ism",$content);
preg_match_all("/【【(.*?)】】/ism",$content,$subjectarr);
if(!isset($subjectarr[1])){
$contentarr=preg_split("/^\s*?.*?第.*?章.*?$/im",$content);
preg_match_all("/^\s*?.*?第.*?章.*?$/im",$content,$subjectarr);
}
if(!isset($subjectarr[1])){
return errorjson(228,'没有找到章节分节符');
}
if(trim($contentarr[0])==''){
unset($contentarr[0]);
$contentarr=array_values($contentarr);
}
// 先清空目录
file_put_contents($txtpath."mulu.txt","");
foreach($subjectarr[1] as $k=>$v){
$v=trim($v);
file_put_contents($txtpath."mulu.txt",$v."\n",FILE_APPEND);
file_put_contents($txtpath.($k+1).".txt","{$v}\n".$contentarr[$k]);
}
// 处理完毕后更新 章节数量 zjnums 和 字数
Db::name('books')->update(['id'=>$book_id,'length'=>mb_strlen($content),'zjnums'=>count($subjectarr[1])]);
return okjson();
}