【问题标题】:apply different styles to different lines of text in PHP [duplicate]将不同的样式应用于PHP中的不同文本行[重复]
【发布时间】:2011-08-25 20:26:29
【问题描述】:

可能重复:
How to get random value out of an array

我有代码将随机字体应用于从 .txt 文件的最后 20 行获取的文本 div。我想对每一行应用一个不同的随机字体...任何指针?

<?php 

$fonts = array("Helvetica", "Arial", "Courier", "Georgia", "Serif", "Comic Sans", "Tahoma");
shuffle($fonts);
$randomFont = array_shift($fonts);

$output = "";
$lines = array_slice(file("users.txt"), -20, 20);

foreach ( $lines as $line )

{
$output .= '<div style="font-family:' . $randomFont . '; margin-left: ' . rand(0, 60) . '%; opacity: 0.8;">' . $line . '</div>';
}

echo $output;
?> 

【问题讨论】:

    标签: php fonts styling


    【解决方案1】:

    现场演示here

    代码:

    $fonts = array("Helvetica", "Arial", "Courier", "Georgia", "Serif", "Comic Sans", "Tahoma");
    shuffle($fonts);
    
    $output = "";
    
    $lines = array();
    for($i = 0; $i < 40; $i++) $lines[] = "line $i";
    
    $i = 0;
    foreach ( $lines as $line ) {
      if($i == count($fonts)) {
        shuffle($fonts);
        $i = 0;
      }
      $output .= '<div style="font-family:' . $fonts[$i] . '; margin-left: ' . rand(0, 60) . '%; opacity: 0.8;">' . $line . "</div>\n";
      $i++;
    }
    
    echo $output;
    

    【讨论】:

      【解决方案2】:

      随机化你的字体:

      $Random = $fonts[rand(0, count($fonts) - 1)];
      

      【讨论】:

        【解决方案3】:

        一直在考虑它并有一个更简单的解决方案。

        <?php
        $fonts = array ('font 1', 'font 2', 'font 3'); // 20 entries for the full set
        
        shuffle ($fonts);
        
        while ($font = array_pop ($fonts))
        {
            $output .= '<div style="font-family:' . $font . ';"></div>';
        }
        ?>
        

        这显然不是您在上面发布的问题的确切解决方案,也不打算这样做。它旨在提供一个获取保证唯一的随机值的方法示例。您应该能够毫不费力地将这里表达的想法合并到您自己的代码中。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-03-18
          • 1970-01-01
          • 1970-01-01
          • 2015-01-07
          相关资源
          最近更新 更多