我需要开发一个PHP功能,其中我有一个数组和最大字符数。
返回一个字符串集合,其中每个字符串元素表示一行,该行包含尽可能多的单词,每行中的单词都用单个"-"连接。每个字符串的长度不得超过每行的最大字符长度。
您的函数应接收每行的最大字符数,并返回一个数据结构,表示指示的最大长度中的所有行。
示例:
words1 = [ "The", "day", "began", "as", "still", "as", "the",
"night", "abruptly", "lighted", "with", "brilliant",
"flame" ]
wrapLines(字1、13(";将字1换行到行长度13〃=>
[ "The-day-began",
"as-still-as",
"the-night",
"abruptly",
"lighted-with",
"brilliant",
"flame" ]
到目前为止,我尝试的是:
foreach ($words1 as $i => $word) {
$a = '';
if($i!= 0 && strlen($a) <= $lineLength1_1){
$a = $a.'-'.$word;
} else {
$a = $word;
}
echo $a;
}
我得到的结果是.
The-day-began-as-still-as-the-night-abruptly-lighted-with-brilliant-flame
有人能帮我如何根据条件检查计数,然后作为结果进入下一个数组键吗?谢谢
您可以使用PHP的wordwrap()
函数来帮助实现这一点:
// $a is an array of strings, $line_length is the max line length
function wrap( $a, $line_length ) {
$r = array_map(
function($s) {
return str_replace( ' ', '-', $s ); // Replace spaces with dashes
},
// Rewrap $a by first joining it into a single string, then explode on newline chars into a new array
explode( "n", wordwrap(join(' ', $a), $line_length ) )
);
return $r;
}
$words1 = [ "The", "day", "began", "as", "still", "as", "the",
"night", "abruptly", "lighted", "with", "brilliant",
"flame" ];
print_r( wrap( $words1, 13 ) );
结果:
Array
(
[0] => The-day-began
[1] => as-still-as
[2] => the-night
[3] => abruptly
[4] => lighted-with
[5] => brilliant
[6] => flame
)
如果你的老师不允许你使用内置的PHP函数,比如wordwrap((,那么你可以使用以下函数:
- 在数组上循环
- 如果字符串长度小于允许的最大值(例如13(,则将每个元素与前一个元素连接起来
- 将连接的字符串推入另一个数组(例如$words2[](
- 返回$words2数组作为结果
因此您可以使用函数wrapLines($words1,13)
,如下所示:
<?php
function wrapLines($words, $maxLineLength) {
$words2=[];
$words1=$words;
$index=0;
$maxlength=$maxLineLength;
$injectstring="";
$olstring="";
while ($index < count($words1)){
if ($injectstring==""){
$tempstring=$words1[$index];
}else{
$tempstring="-".$words1[$index];
}
$oldstring=$injectstring;
if (strlen($injectstring) < $maxlength) {
$injectstring=$injectstring . $tempstring;
}
if (strlen($injectstring) == $maxlength) {
$words2[]= $injectstring ;
$injectstring="";
}
if (strlen($injectstring) > $maxlength) {
$words2[]= $oldstring ;
$injectstring=$words1[$index];
}
$index++;
}
$words2[]= $injectstring ."<br>";
return($words2);
}
$words1 = [ "The", "day", "began", "as", "still", "as", "the",
"night", "abruptly", "lighted", "with", "brilliant",
"flame" ];
print_r(wrapLines($words1,13));
?>