How to format plaintext like a book/magazine with PHP?

前端 未结 2 1809
面向向阳花
面向向阳花 2021-01-28 04:20

I have:

This is a test string. Cool, huh?

I want:

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

That is, each line is

2条回答
  •  我在风中等你
    2021-01-28 05:05

    Here's some code you should be able to work with, using some sort of hyphenation library. This code uses a fake 3-character hyphenation function. You can see it in action at https://www.tehplayground.com/eNtxiMTeXj16oPkT - it took me about 10 minutes to write this, so it was, in fact, trivial - contrary to what you wrote in the now deleted thread.

    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);
    

提交回复
热议问题