如何在不中断单词的情况下拆分长字符串? [英] How to split a long string without breaking words?

查看:34
本文介绍了如何在不中断单词的情况下拆分长字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找类似的东西

str_split_whole_word($longString, $x)

其中$longString 是句子的集合,$x 是每行的字符长度.它可以相当长,我想基本上以数组的形式将其拆分为多行.

Where $longString is a collection of sentences, and $x is the character length for each line. It can be fairly long, and I want to basically split it into multiple lines in the form of an array.

例如:

$longString = 'I like apple. You like oranges. We like fruit. I like meat, also.';
$lines = str_split_whole_word($longString, $x);

所需的输出:

$lines = Array(
    [0] = 'I like apple. You'
    [1] = 'like oranges. We'
    [2] = and so on...
)

推荐答案

这段代码避免了断词,你不会用 wordwrap() 得到它.

This code avoid breaking words, you won't get it using wordwrap().

使用$maxLineLength 定义最大长度.我做了一些测试,效果很好.

The maximum length is defined using $maxLineLength. I've done some tests and it works fine.

$longString = 'I like apple. You like oranges. We like fruit. I like meat, also.';

$words = explode(' ', $longString);

$maxLineLength = 18;

$currentLength = 0;
$index = 0;

foreach ($words as $word) {
    // +1 because the word will receive back the space in the end that it loses in explode()
    $wordLength = strlen($word) + 1;

    if (($currentLength + $wordLength) <= $maxLineLength) {
        $output[$index] .= $word . ' ';
        $currentLength += $wordLength;
    } else {
        $index += 1;
        $currentLength = $wordLength;
        $output[$index] = $word;
    }
}

这篇关于如何在不中断单词的情况下拆分长字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆