Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- $input = "book.in";
- $output = "book.out";
- $chars_per_line = 60;
- $margin_left = 0;
- $margin_right = 0;
- $red_line = 5;
- define("NBSP","~");
- function is_punct($char){
- return $char=="," || $char=="." || $char=="-" || $char=="—" || $char==";" || $char==":" || $char=="!" || $char=="?" || $char==")";
- }
- function is_space($char){
- return $char==" " || $char=="\t" || $char=="\r" || $char=="\n";
- }
- function sp($n){
- return str_repeat(" ",$n);
- }
- function crop($line,$len){
- if(mb_strlen($line)<=$len)
- return $line;
- $line=mb_substr($line,0,$len);
- $i=mb_strlen($line)-1;
- while($i>=2 && !is_space(mb_substr($line,$i,1)) )
- $i--;
- $line=trim(mb_substr($line,0,$i));
- return $line;
- }
- function justify($line,$len){
- $line=trim($line);
- $words=mb_split("\s+",$line);
- $total=0;
- $deficite=$len;
- $factors=array();
- for($i=0;$i<count($words)-1;$i++){
- $this_word=$words[$i];
- $next_word=$words[$i+1];
- $l1=mb_strlen($this_word);
- $l2=mb_strlen($next_word);
- $factor = is_punct(mb_substr($this_word,-1,1)) ? max($l1-1,$l2) : min($l1,$l2);
- $total+=$factor;
- $deficite -= $l1+1;
- $factors[$i]=$factor;
- }
- $deficite -= mb_strlen($words[count($words)-1]);
- $ret="";
- for($i=0;$i<count($words)-1;$i++){
- $n=round($deficite*$factors[$i]/$total);
- $ret.=$words[$i].sp($n+1);
- $deficite-=$n;
- $total-=$factors[$i];
- }
- $ret.=sp($deficite).$words[count($words)-1];
- return $ret;
- }
- function preprocess($line){
- $line=mb_ereg_replace("(\s|".NBSP.")([а-яёА-ЯЁ]|Не|Ни|не|ни)\s+","\\1\\2".NBSP,$line);
- $line=mb_ereg_replace("(\s|".NBSP.")([а-яёА-ЯЁ]|Не|Ни|не|ни)\s+","\\1\\2".NBSP,$line);
- $line=mb_ereg_replace("(\s|".NBSP.")([а-яёА-ЯЁ]|Не|Ни|не|ни)\s+","\\1\\2".NBSP,$line);
- return $line;
- }
- function postprocess($line){
- $line=mb_ereg_replace(NBSP," ",$line);
- return $line;
- }
- function process($line,$len,$spaces){
- global $outfile;
- $line = trim($line);
- $line = preprocess($line);
- $subline = postprocess(crop($line,$len));
- $line = mb_substr($line,mb_strlen($subline));
- if($line){
- $char=mb_substr($subline,-1,1);
- if(is_punct($char))
- $len++;
- $subline = justify($subline,$len);
- }
- fwrite($outfile,$spaces.$subline."\n");
- return $line;
- }
- $len = $chars_per_line-$margin_right-$margin_left;
- $len1 = $len-$red_line;
- $spaces = sp($margin_left);
- $spaces1 = sp($margin_left+$red_line);
- mb_internal_encoding("UTF-8");
- $infile = fopen($input,"r");
- $outfile = fopen($output,"w");
- $i=0;
- while(($line=fgets($infile))!==FALSE){
- $line=process($line,$len1,$spaces1);
- while($line){
- $line=process($line,$len,$spaces);
- }
- }
- fclose($infile);
- fclose($outfile);
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement