如何使用PHP将纯文本格式设置为书籍/杂志?

问题描述 投票:0回答:2
我有:

This is a test string. Cool, huh?

我想要:

This is a te- st string. C- ool, huh?

也就是说,每行正好是13个字符,

根据此英语规则。也就是说,我不确定是否可以像“ te-st”那样拆分“ test”,还是可以将“ Cool”拆分成“ C-ool”,但这就是我要尝试的“样式”实现。

我已经进行了大约一千次搜索查询。我什么也没找到。

wordwrap()是无用的,因为它仅适用于整个“单词”,并在大多数行的末尾留有大量的空白。

这实在令人沮丧,因为在解决之前,我无法继续我的项目。我以为会有一个库,但是我发现唯一甚至与远程相关的是https://github.com/vanderlee/phpSyllable,但这似乎根本没有做到这一点。该示例没有任何意义,因为它不显示任何输出,并且在任何地方都没有提及任何行“宽度”。

php formatting plaintext text-manipulation
2个回答
1
投票
HyphenatorOrg_Heigl/Hyphenator库似乎在正确处理连字符。基于其中之一,您应该可以编写自己的wordwrap(),该字符可以使用空格或连字符作为断点。

请注意,英语单词具有非常特定的连字符点,因此绝对不能保证每一行的长度都精确地

n个字符。如果下一个音节恰好很长,有时您会缺少几个字符-例如“ thorough”连字符为thor-ough,而“ through”根本不连字符。


0
投票
以下是使用某种断字库可以使用的一些代码。此代码使用伪造的3个字符的连字符函数。您可以在https://www.tehplayground.com/eNtxiMTeXj16oPkT处看到它的运行情况-我花了大约10分钟的时间编写了它,因此,实际上这是微不足道的-与您在现在删除的线程中编写的内容相反。

<?php $loremipsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."; function FAKE_hyphenate($word) { // use some real library's hyphenation function here return explode("-",wordwrap($word,3,"-",true)); } function hyphenate_text ($text, $line_length) { $words = explode(" ",$text); $lines = [str_repeat("-",$line_length)]; $line = ""; while ($words) { $word = array_shift($words); if (strlen($line)+strlen($word)+1<=$line_length) $line .= (strlen($line)>0 ? " " : "") . $word; else { $syllables = FAKE_hyphenate($word); $syllables[0] = " ".$syllables[0]; $syl_count=0; while ($syllables) { $syllable = array_shift($syllables); if (strlen($line)+strlen($syllable)<=$line_length-1) { $line .= $syllable; $syl_count++; } else { array_unshift($syllables,$syllable); break; } } if ($syl_count>0) $line .= "-"; $syllables[0] = str_replace(" ","",$syllables[0]); array_unshift($words,implode("",$syllables)); $lines[] = $line; $line = ""; } } $lines[] = $line; return implode("\n",$lines); } echo hyphenate_text($loremipsum,25);

© www.soinside.com 2019 - 2024. All rights reserved.