【问题标题】:im trying to figure out how to create a new line whenever an array value reaches more than 10 characters我试图弄清楚当数组值超过 10 个字符时如何创建新行
【发布时间】:2013-11-15 04:10:43
【问题描述】:

这是我的代码,但它不是动态的,我需要的是如果数组值大于 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];
}


?>

【问题讨论】:

  • 不完全清楚你在问什么... - 但是如果你一次循环遍历你的字符串一个字符并在字符数模 10 等于 0 时插入 newLine 会怎样?
  • 您能否展示一个示例标题和您期望的输出...

标签: php arrays for-loop newline


【解决方案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;

【讨论】:

  • 很好的尝试,但您的输出中缺少一些单词?? “到”、“如何”、“一个”、“无论何时”……
  • @Floris 我在发布我的答案并立即更新后才意识到。不过谢谢你的指点。
猜你喜欢
  • 2016-01-27
  • 1970-01-01
  • 2021-03-24
  • 2016-03-11
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 2012-10-05
  • 2016-10-04
相关资源
最近更新 更多