我正在寻找一些东西
str_split_whole_word($longString, x)
Run Code Online (Sandbox Code Playgroud)
where $longString
是句子的集合,x
是每一行的字符长度.它可能相当长,我想基本上以数组的形式将它分成多行.
所以,例如,
$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...
)
Run Code Online (Sandbox Code Playgroud)
nic*_*ckb 48
最简单的解决方案是使用wordwrap()
,并explode()
在新的生产线,就像这样:
$array = explode( "\n", wordwrap( $str, $x));
Run Code Online (Sandbox Code Playgroud)
$x
包含字符串的字符数在哪里.
Mar*_*ato 17
这个解决方案可以确保创建行而不会破坏单词,使用wordwrap()将无法获得.它将使用空间来爆炸字符串,然后使用foreach循环数组并创建行而不会破坏工作并使用最大长度$maxLineLength
.下面是代码,我做了一些测试,它工作正常.
$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;
}
}
Run Code Online (Sandbox Code Playgroud)
Mic*_*ski 11
使用wordwrap()
插入换行符,然后explode()
对这些换行:
// Wrap at 15 characters
$x = 15;
$longString = 'I like apple. You like oranges. We like fruit. I like meat, also.';
$lines = explode("\n", wordwrap($longString, $x));
var_dump($lines);
array(6) {
[0]=>
string(13) "I like apple."
[1]=>
string(8) "You like"
[2]=>
string(11) "oranges. We"
[3]=>
string(13) "like fruit. I"
[4]=>
string(10) "like meat,"
[5]=>
string(5) "also."
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
30937 次 |
最近记录: |