$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;