【问题标题】:Add a word break tag after every 12th character in a string在字符串中的每 12 个字符后添加一个分词标记
【发布时间】:2012-09-04 07:00:59
【问题描述】:
$my_string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry."

预期结果:

"Lorem Ipsum <br/> is simply<br/> dummy text<br/>of the printing<br/> and typesetting<br/> industry."

标签应该在每 12 个字符之后添加,而不是这样:

There are ma<br/>ny variations

【问题讨论】:

  • 你是说12个字之后?
  • 您确定需要添加br 并且不使用CSS 进行文本换行吗?

标签: php html string


【解决方案1】:

试试wordwrap。我认为它应该可以解决您的问题。

【讨论】:

    【解决方案2】:

    试试这个

    $newtext = wordwrap($text,12, "<br />");
    

    【讨论】:

      【解决方案3】:
      $text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry.";
      $newtext = wordwrap($text, 12, "<br />\n");
      
      echo $newtext;
      

      输出:

      Lorem Ipsum
      is simply
      dummy text
      of the
      printing and
      typesetting
      industry. 
      
      
      http://www.php.net/manual/en/function.wordwrap.php
      

      【讨论】:

      【解决方案4】:

      只是用一个例子来扩展 Shakti 的答案:

      $my_string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry.";
      $my_wrapped_string = wordwrap($my_string, 12, '<br />');
      

      $my_wrapped_string 的值将是 Lorem Ipsum&lt;br /&gt;is simply&lt;br /&gt;dummy text&lt;br /&gt;of the&lt;br /&gt;printing and&lt;br /&gt;typesetting&lt;br /&gt;industry.

      【讨论】:

        【解决方案5】:

        您的预期结果在空格和中断方面似乎非常不一致。听起来你想要一些定制的解决方案,你所追求的更像是这样的:

        $array = $my_string.explode(" ");
        
        counter = 0;
        for(index=0; index<array.length; index++){
            counter += array[index].length+1;
            if(counter > 12){
                array[index-1] += "<br>"; //put some error handling here
                counter = 0;
            }
        }
        
        //then convert back to string and do whatever 
        // - I tested this in JS and it worked fine
        

        【讨论】:

          【解决方案6】:
          <?php
          $text = "A very long woooooooooooooooooord. and something";
          $newtext = wordwrap($text, 8, "\n", false);
          
          echo "$newtext\n";
          ?>
          

          上面的例子会输出:

          A very
          long
          woooooooooooooooooord.
          and
          something
          

          【讨论】:

          • $str = "一个长词的例子是:Supercalifragulistic"; echo wordwrap($str,12,"
            \n");
          猜你喜欢
          • 1970-01-01
          • 2017-07-25
          • 1970-01-01
          • 2014-04-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多