wordwrap, chunk_split or something else can help me?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nhbach
    New Member
    • Dec 2009
    • 7

    #1

    wordwrap, chunk_split or something else can help me?

    Hi all,
    How to break line of long string including inside html code?

    Example
    I have a long string of letters AAAAAAAACCCCCCC CC and they was formated with html code.
    Code:
    <font color=magenta>AAAAAAAAA</font><font color=red>CCCCCCCCCC</font>
    How to break line each 4 letters (still keep the color of these letters). I was used wordwrap, chunk_split but failed. Please help me, thanks!
  • Atli
    Recognized Expert Expert
    • Nov 2006
    • 5062

    #2
    Hey.

    You could just go through the string manually and add line-breaks at the appropriate positions. You would just have to loop through each character in the string, detect whether or not it is inside a HTML tag, and if it is not, count it. And then you would just add a "<br>" every time the counter reaches 4.

    For example:
    [code=php]<?php
    $input = "<font color=magenta>A AAAAAAAA</font><font color=red>CCCCC CCCCC</font>";
    $output = '';

    $tag_open = false;
    $letter_counter = 0;
    $input_length = strlen($input);

    for($i = 0; $i < $input_length; ++$i)
    {
    // Check if the current letter is a opening or closing tag.
    if($input[$i] == ">" || $input[$i] == "<")
    {
    // It is! Change the $open boolean so that the next
    // loop knows that a tag open/close was detected.
    $tag_open = !$tag_open;
    }
    else
    {
    // Check if the current letter is inside a tag.
    if(!$tag_open)
    {
    // Check if the current character count is at 4
    if($letter_coun ter == 4)
    {
    // Add a line-break and reset the count
    $output .= "<br>";
    $letter_counter = 0;
    }
    // Add the current letter to the cycle count.
    ++$letter_count er;
    }
    }

    // Add the current letter to the output string.
    $output .= $input[$i];
    }

    echo $output;
    ?>[/code]
    Prints:
    [code=html]<font color=magenta>A AAA<br>AAAA<br> A</font><font color=red>CCC<b r>CCCC<br>CCC</font>[/code]

    And also, you should try to avoid using old HTML tags like <font> to format your pages. It's generally better to use CSS.
    [code=html]
    # Instead of doing:
    <font color="red">ABC D</font>
    # Do:
    <span style="color: red;">ABCD</span>[/code]
    Or better yet:
    [code=html]<!DOCTYPE html>
    <head>
    <title>CSS Example</title>
    <style type="text/css">
    span.red {
    color: red;
    }
    </style>
    </head>
    <body>
    <span class="red">ABC D</span>
    </body>
    </html>[/code]

    Comment

    • nhbach
      New Member
      • Dec 2009
      • 7

      #3
      You're great! Thank you so much, i can resolve my probleme!

      Comment

      Working...