Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Sep 2012
    Posts
    15
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Converting plain text into html paragraphs

    I'm trying to write a function that converts plain text into paragraphs wrapped around <p> tags. Here's an input/output example:

    Input:

    $text = <<< OUT
    Paragraph 1

    Paragraph 2

    Paragraph 3
    OUT;

    Output:
    $text = <<< OUT
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <p>Paragraph 3</p>
    OUT;

    Can anyone give me a helping hand? Thanks a lot.

  • #2
    Regular Coder Arcticwarrio's Avatar
    Join Date
    May 2012
    Location
    UK
    Posts
    721
    Thanks
    20
    Thanked 84 Times in 84 Posts
    PHP Code:
    <?php
    //Input:

    $text "<<< OUT
    Paragraph 1

    Paragraph 2

    Paragraph 3
    OUT;"
    ;

    function 
    P_Convertor($input){
        
    $output '';
        
    $lines explode("\n\r",$input);
        foreach (
    $lines as $k => $v){
            
    $output .= "<p>".str_replace("\n\r"""$v)."</p>".PHP_EOL;
        }
        return 
    $output;
    }

    $test P_Convertor($text);
    echo 
    $test;
    ?>
    There are 10 types of people on CodingForums,
    Those who understand Binary and those who dont.
    Get Cloud Hosting now from only£59 / month

  • #3
    Senior Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Location
    Behind the Wall
    Posts
    3,253
    Thanks
    12
    Thanked 341 Times in 337 Posts
    another option (without a loop):
    PHP Code:
    $lines explode("\n"$input);

    // explode contains some empty lines, hence
    array_walk($lines"trim");

    // filter off empty elements
    $lines array_filter($lines);

    // concat the elements back together
    $out "<p>" implode("</p><p>"$lines) . "</p>"
    The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
    André Behrens, NY Times Software Developer


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •