0

这是我的代码,但它不是动态的,我需要的是如果数组值大于 10,它将自动创建新行...谢谢

<?php
$limit = 10;
$newline = explode(" ",$caption); 
array_map(null, $newline);

$count = count($newline); //count number of array values



$nlimit = strlen($newline[0]) + strlen($newline[1]);

if($limit >= $nlimit)
{
    echo $newline[0] . " ",$newline[1];
}
else
{
    echo $newline[0] . " ","<br>". $newline[1];
}


?>
4

1 回答 1

1
$caption = "im trying to figure out how to create a new line whenever an array value reaches more than 10 characters";

$lineCharlimit = 10;

$captionWordsArray = explode( " " ,$caption ); 

$line = '';

foreach( $captionWordsArray as $index => $word )
{
    if( strlen( $line .$word ) > $lineCharlimit )
    {
        echo $line ,'<br>';
        $line = $word;
    }
    else
    {
        $line .= ( $line == '' ? '' : ' ' ) .$word;
    }
}
echo $line;

将输出:

im trying
to figure
out how to
create a
new line
whenever an
array value
reaches
more than
10
characters

但是对于像下面这样的输出(没有一行少于 10 个字符,除非它是最后一个单词):

im trying to
figure out how
to create a
new line whenever
an array value
reaches more
than 10 characters

修改代码如下:

$caption = "im trying to figure out how to create a new line whenever an array value reaches more than 10 characters";

$lineCharlimit = 10;

$captionWordsArray = explode( " " ,$caption ); 

$line = '';

foreach( $captionWordsArray as $index => $word )
{
    $line .= ( $line == '' ? '' : ' ' ) .$word;

    if( strlen( $line ) > $lineCharlimit )
    {
        echo $line ,'<br>';
        $line = '';
    }
}
echo $line;
于 2013-11-15T05:57:32.923 回答