簡體   English   中英

PHP中更智能的自動換行用於長詞?

[英]Smarter word-wrap in PHP for long words?

我正在尋找一種方法讓PHP中的自動換行更智能一點。 因此,它不會預先打破長字,只留下任何先前的小字在一行上。

假設我有這個(真正的文本總是完全動態的,這只是為了顯示):

wordwrap('hello! heeeeeeeeeeeeeeereisaverylongword', 25, '<br />', true);

這輸出:

你好!
heeeeeeeeeeeeeeereisavery
長字

看,它在第一行留下了單詞。 我怎樣才能讓它輸出更像這樣的東西:

你好! heeeeeeeeeeee
eeereisaverylongword

因此它利用每條線上的任何可用空間。 我已經嘗試了幾個自定義函數,但沒有一個是有效的(或者它們有一些缺點)。

我已經開始使用這個智能文字包裝的自定義功能了:

function smart_wordwrap($string, $width = 75, $break = "\n") {
    // split on problem words over the line length
    $pattern = sprintf('/([^ ]{%d,})/', $width);
    $output = '';
    $words = preg_split($pattern, $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);

    foreach ($words as $word) {
        if (false !== strpos($word, ' ')) {
            // normal behaviour, rebuild the string
            $output .= $word;
        } else {
            // work out how many characters would be on the current line
            $wrapped = explode($break, wordwrap($output, $width, $break));
            $count = $width - (strlen(end($wrapped)) % $width);

            // fill the current line and add a break
            $output .= substr($word, 0, $count) . $break;

            // wrap any remaining characters from the problem word
            $output .= wordwrap(substr($word, $count), $width, $break, true);
        }
    }

    // wrap the final output
    return wordwrap($output, $width, $break);
}

$string = 'hello! too long here too long here too heeeeeeeeeeeeeereisaverylongword but these words are shorterrrrrrrrrrrrrrrrrrrr';
echo smart_wordwrap($string, 11) . "\n";

編輯 :發現了一些警告。 對此(以及本機功能)的一個主要警告是缺少多字節支持。

怎么樣

$string = "hello! heeeeeeeeeeeeeeereisaverylongword";
$break = 25;

echo implode(PHP_EOL, str_split($string, $break));

哪個輸出

hello! heeeeeeeeeeeeeeere                                                                                                                                                           
isaverylongword

str_split()將字符串轉換為$ break size塊的數組。

implode()使用膠水將數組作為字符串連接在一起,在這種情況下,膠水是行尾標記(PHP_EOL),盡管它可以很容易地成為' <br/> '

這也是一個解決方案(對於瀏覽器等):

$string = 'hello! heeeeeeeeeeeeeeeeeeeeeereisaverylongword';
echo preg_replace('/([^\s]{20})(?=[^\s])/', '$1'.'<wbr>', $string);

它將<wbr>放在包含20個或更多字符的單詞上

<wbr>表示“分詞機會”,因此只有在必須時才會中斷(由元素/瀏覽器/查看器/其他的寬度決定)。 否則它是看不見的。

適用於沒有固定寬度的流暢/響應式布局。 並不像php的wordwrap那樣包裹奇怪

您可以使用CSS來完成此任務。

word-wrap: break-word;

那會打破你的話。 這是一個鏈接,可以看到它的實際效果:

http://www.css3.info/preview/word-wrap/

這應該是訣竅......

$word = "hello!" . wordwrap('heeeeeeeeeeeeeeereisaverylongword', 25, '<br />', true);
echo $word;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM