本文介绍了PHP:拆分长字符串而不会断词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找与
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;
}
}
这篇关于PHP:拆分长字符串而不会断词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!