Converting <br/> to \n and Back Again (Textarea)

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • cheezylu
    New Member
    • Feb 2007
    • 6

    Converting <br/> to \n and Back Again (Textarea)

    I'm working on a site where my client will be able to maintain some of the text on the site using input boxes and such driven by PHP and MySQL. The problem I am running into is making it easy for them to enter text into a textarea and have it automatically format the "<br/>" tags from their return strokes ("\n" in the textarea). I know how to convert the \n's to "<br/>" when a new item is added into the database using "str_replac e". However, when they go to edit that field later on, I need it to convert the "<br/>"'s back to \n's (in a textarea) so it returns the original formatting they typed in and they don't have to worry about any code.
  • stephane
    New Member
    • Feb 2007
    • 35

    #2
    nl2br()
    or, simply
    str_replace()

    Comment

    • ronverdonk
      Recognized Expert Specialist
      • Jul 2006
      • 4259

      #3
      Not that simple. <b> tags can have 3 different formats, so you have to cope with all of them. You could use a regular expression, but the following will make it more clear:

      [php]$new_string=str _replace(array( "<br>","<br/>","<br />"), array("\n","\n" ,"\n"), $old_test);[/php]

      Ronald :cool:

      Comment

      • Motoma
        Recognized Expert Specialist
        • Jan 2007
        • 3236

        #4
        Originally posted by ronverdonk
        Not that simple. <b> tags can have 3 different formats, so you have to cope with all of them. You could use a regular expression, but the following will make it more clear:

        [php]$new_string=str _replace(array( "<br>","<br/>","<br />"), array("\n","\n" ,"\n"), $old_test);[/php]

        Ronald :cool:
        Is str_replace case sensitive? If so, there are a lot more combinations to take into account!
        Just thought I would throw that in there; regular expressions are probably the best way to go with this.

        Comment

        • cheezylu
          New Member
          • Feb 2007
          • 6

          #5
          Originally posted by ronverdonk
          [php]$new_string=str _replace(array( "<br>","<br/>","<br />"), array("\n","\n" ,"\n"), $old_test);[/php]
          That is what I thought since it made sense just to use the same method to switch it back, but the new variable (ex: $new_string) appears to be blank when I try to print it to the page. Is there a secret to where this code needs to be placed?

          Comment

          • Motoma
            Recognized Expert Specialist
            • Jan 2007
            • 3236

            #6
            The following code works for me:

            [PHP]
            <?php

            $text = "This is some<br>crazy multi<br />lined text<br/><br><br>ohyes" ;
            print "$text<hr>" ;

            $new_text = str_replace(arr ay("<br>","<br/>","<br />"), array("\n","\n" ,"\n"), $text);
            print "$new_text<hr>" ;

            $restored_text = str_replace("\n ", "<br />", $new_text);
            print $restored_text;

            ?>
            [/PHP]

            Note: If you are using PHP 5 +, you can use str_ireplace for case insensitive replacement.

            Comment

            • cheezylu
              New Member
              • Feb 2007
              • 6

              #7
              I am using PHP 5.1.5

              It still isn't working for me. Is there a special spot it needs to be placed in the code or does it matter that I'm pulling the text from a SQL database (longtext)?

              Comment

              • Motoma
                Recognized Expert Specialist
                • Jan 2007
                • 3236

                #8
                Originally posted by cheezylu
                I am using PHP 5.1.5

                It still isn't working for me. Is there a special spot it needs to be placed in the code or does it matter that I'm pulling the text from a SQL database (longtext)?
                Shouldn't matter.
                Did the code I pasted in work?

                Comment

                • cheezylu
                  New Member
                  • Feb 2007
                  • 6

                  #9
                  Originally posted by Motoma
                  Shouldn't matter.
                  Did the code I pasted in work?
                  Yes, the code worked when I placed it as is. However, when I tried to plug in "$body" which is the field I am aiming to work with, it produced blank results. Here is my code. there are two pages needed. stories.php lists all records in the table and when you click on the "Edit" button you are directed to stories_update. php which will be the edit page for whichever item you select.

                  [PHP]
                  // stories.php

                  <?php include 'header.php'; ?>


                  <?php session_start() ;
                  header("Cache-control: private"); // IE6 fix for sessions
                  ?>


                  <form method="POST" action="stories .php">
                  <table class=\"clear\" >
                  <tr>
                  <td>Title:</td><td><input type="text" name="title"><i nput type="SUBMIT" value="Search!" style=\"display :inline; margin-top:0px; margin-bottom:0px;\"></td>
                  </tr>
                  </table>
                  </form>

                  <br>


                  <?php
                  session_destroy ();


                  //Setting session variables
                  if( isset( $_POST[ 'title' ] ) )
                  {
                  $_SESSION['title'] = $_POST['title'];
                  }



                  //display search query
                  if ($title == ""){
                  echo("");
                  } else {
                  echo("
                  <table border=0 bgcolor=#ff6600 ><tr><td><fon t color=white>
                  You're searching for...<br>
                  ");
                  }

                  if ($title != ""){ echo("&nbsp;&nb sp;&nbsp;&nbsp; &nbsp; Title: ".$title."<br>" );}

                  if ($title == ""){
                  echo("");
                  } else {
                  echo("
                  </font></td></tr></table>
                  <table cellpadding=0 cellspacing=0>< tr><td>
                  <form method=POST action=stories. php>
                  <input type=hidden name=title value=\"\">
                  <input type=SUBMIT value=\"Clear Search Parameters\">
                  </form>
                  </td></tr></table><br>
                  ");
                  }
                  // END of search query



                  // PHP Search Script
                  $username="***U SERNAME***";
                  $password="***P ASSWORD***";
                  $database="***D ATABASE***";


                  mysql_connect(" ***SQL***",$use rname,$password );
                  @mysql_select_d b($database) or die( "Unable to select database");

                  $sql = mysql_query("SE LECT * FROM stories WHERE title LIKE '%$title%' ORDER BY title ASC") or die (mysql_error()) ;

                  //Is displayed if there is no data to return
                  if(mysql_num_ro ws($sql) == 0){
                  echo("<br><br>< br><b>No results found...</b><br><br>
                  Try widening your search a bit. :)
                  <br><br><br><br ><br><br>");
                  }
                  // This reads the number of rows returned from the result above.


                  echo "

                  <table><tr><T D BACKGROUND=\"ht tp://www.cheezylu.co m/cheezylu/images/clear.gif\" align=\"center\ ">
                  <table cellpadding=\"1 \" cellspacing=\"0 \" bgcolor=\"#0000 00\" BORDER=0><TR><T D>
                  <table cellpadding=\"5 \" cellspacing=\"0 \" border=\"0\">

                  <tr bgcolor=\"#dee8 f1\">
                  <td align=\"left\" colspan=\"4\">
                  <div class=\"txtTitl e\" align=\"center\ ">Story Listing</div>
                  </td>
                  </tr>
                  ";

                  $j=0;
                  while(list($id, $topic, $date, $author, $title, $blurb, $body, $imgTitle, $img, $imgType)=mysql _fetch_array($s ql)){

                  if (is_int($j / 2)) {

                  echo "

                  <tr bgcolor=\"fffff f\">
                  <td nowrap>";

                  if ($img == "")
                  {
                  echo "no image";
                  } else
                  echo "<img src=\"stories_i mage.php?id=$id \" height=\"50\" width=\"50\">";

                  echo " </td>
                  <td>
                  <b>$title</b>
                  </td>
                  <td>
                  <form method=\"POST\" action=\"storie s_update.php\">
                  <input type=\"hidden\" name=\"e_id\" value=\"$id\">
                  <input type=\"submit\" value=\"Edit\" style=\"display :inline; margin-top:0px; margin-bottom:0px;\">
                  </form>
                  </td>
                  <td>
                  <form method=\"POST\" action=\"storie s_delete.php\">
                  <input type=\"hidden\" name=\"de_id\" value=\"$id\">
                  <input type=\"submit\" value=\"Delete\ " style=\"display :inline; margin-top:0px; margin-bottom:0px;\">
                  </form>
                  </td>
                  </tr>

                  ";

                  } else {

                  echo "

                  <tr bgcolor=\"#f2f2 f2\">
                  <td nowrap>";

                  if ($img == "")
                  {
                  echo "no image";
                  } else
                  echo "<img src=\"stories_i mage.php?id=$id \" height=\"50\" width=\"50\">";

                  echo " </td>
                  <td>
                  <b>$title</b>
                  </td>
                  <td>
                  <form method=\"POST\" action=\"storie s_update.php\">
                  <input type=\"hidden\" name=\"e_id\" value=\"$id\">
                  <input type=\"submit\" value=\"Edit\" style=\"display :inline; margin-top:0px; margin-bottom:0px;\">
                  </form>
                  </td>
                  <td>
                  <form method=\"POST\" action=\"storie s_delete.php\">
                  <input type=\"hidden\" name=\"de_id\" value=\"$id\">
                  <input type=\"submit\" value=\"Delete\ " style=\"display :inline; margin-top:0px; margin-bottom:0px;\">
                  </form>
                  </td>
                  </tr>

                  ";

                  } //end of else

                  $j++;


                  } //end of while


                  echo "</table>
                  </td></tr></table>
                  </td></tr></table>";
                  ?>


                  <?php include 'footer.php'; ?>
                  [/PHP]

                  [PHP]
                  // stories_update. php

                  <?php include 'header.php'; ?>


                  <?php session_start() ;
                  header("Cache-control: private"); // IE6 fix for sessionsÊÊ
                  ?>


                  <form enctype="multip art/form-data" name="frmUpload File" action="stories _updated.php" method="post">

                  <table border="0"><tr> <TD BACKGROUND=\"ht tp://www.cheezylu.co m/cheezylu/images/clear.gif\" align=\"center\ ">
                  <table cellpadding=\"1 \" cellspacing=\"0 \" bgcolor=\"#0000 00\" BORDER=0><TR><T D>
                  <table cellpadding=\"5 \" cellspacing=\"0 \" border=\"0\">

                  <tr bgcolor="#ccccc c">
                  <td colspan="2"><b> Update Story</b></td>
                  </tr>

                  <tr bgcolor="#f2f2f 2">
                  <td>Topic:</td>
                  <td>
                  <input type="radio" name="topicType " size="20" value="new">New Topic &nbsp;&nbsp;<in put type="text" name="ud_topicN ew" size="20" maxlength="50"> <br/>
                  <input type="radio" name="topicType " size="20" value="old" checked>Existin g Topic &nbsp;&nbsp;
                  <select name="ud_topicO ld">


                  <?php

                  // Database connection variables
                  $dbServer = "***SQL***" ;
                  $dbDatabase = "***DATABASE*** ";
                  $dbUser = "***USERNAME*** ";
                  $dbPass = "***PASSWORD*** ";

                  $sConn = mysql_connect($ dbServer, $dbUser, $dbPass)
                  or die("Couldn't connect to database server");

                  $dConn = mysql_select_db ($dbDatabase, $sConn)
                  or die("Couldn't connect to database $dbDatabase");

                  $dataPull = "SELECT topic FROM stories WHERE id LIKE '$e_id'";

                  //Pulls what we want from the database
                  $data = mysql_query($da taPull) or die("Couldn't get file list");

                  $j=0;
                  while(list($top ic)=mysql_fetch _array($data)){

                  echo "

                  <option value=\"$topic\ ">$topic *</option>";

                  $j++;

                  } //end of while


                  $dataTopicPull = "SELECT DISTINCT topic FROM stories";

                  //Pulls what we want from the database
                  $dataTopic = mysql_query($da taTopicPull) or die("Couldn't get file list");

                  $j=0;
                  while(list($top ic)=mysql_fetch _array($dataTop ic)){

                  echo "

                  <option value=\"$topic\ ">$topic</option>";

                  $j++;

                  } //end of while

                  ?>

                  </select>

                  </td>
                  </tr>



                  <?php

                  $dataContentPul l = "SELECT * FROM stories WHERE id LIKE '$e_id'";

                  //Pulls what we want from the database
                  $dataContent = mysql_query($da taContentPull) or die("Couldn't get file list");

                  //$restored_text = str_replace("\n ", "<br />", $body);

                  $m=0;
                  while(list($id, $topic, $date, $author, $title, $blurb, $body, $imgTitle, $img, $imgType)=mysql _fetch_array($d ataContent)){

                  echo "
                  <tr bgcolor=\"#ffff ff\">
                  <td>Date:</td>
                  <td>
                  <input type=\"text\" name=\"ud_date\ " size=\"15\" maxlength=\"50\ " value=\"$date\" > ex: 000-00-00
                  </td>
                  </tr>

                  <tr bgcolor=\"#f2f2 f2\">
                  <td>Author:</td>
                  <td>
                  <input type=\"text\" name=\"ud_autho r\" size=\"30\" maxlength=\"50\ " value=\"$author \">
                  </td>
                  </tr>

                  <tr bgcolor=\"#ffff ff\">
                  <td>Story Title:</td>
                  <td>
                  <input type=\"text\" name=\"ud_title \" size=\"30\" maxlength=\"50\ " value=\"$title\ ">
                  </td>
                  </tr>

                  <tr bgcolor=\"#f2f2 f2\">
                  <td>Blurb:</td>
                  <td>
                  <input type=\"text\" name=\"ud_blurb \" size=\"30\" maxlength=\"100 \" value=\"$blurb\ ">
                  </td>
                  </tr>

                  <tr bgcolor=\"#ffff ff\">
                  <td valign=\"top\"> Story:</td>
                  <td>
                  <textarea name=\"ud_body\ " cols=\"30\" rows=\"10\">$bo dy</textarea>
                  </td>
                  </tr>

                  <tr bgcolor=\"#f2f2 f2\">
                  <td>File Description:</td>
                  <td>
                  <input type=\"text\" name=\"ud_imgTi tle\" size=\"30\" maxlength=\"50\ " value=\"$imgTit le\">
                  </td>
                  </tr>

                  <tr bgcolor=\"#ffff ff\">
                  <td valign=\"top\"> Update Image:</td>
                  <td>
                  <input type=\"radio\" name=\"imgUpdat e\" value=\"clear\" >Clear Image<br/>
                  <input type=\"radio\" name=\"imgUpdat e\" value=\"n\" checked>No<br/>
                  <input type=\"radio\" name=\"imgUpdat e\" value=\"y\">Yes &nbsp;&nbsp;
                  <input type=\"file\" name=\"fileUplo ad\" size=\"20\"><br/>
                  </td>
                  </tr>

                  <tr bgcolor=\"#f2f2 f2\">
                  <td colspan=\"2\" align=\"center\ ">
                  <input type=\"hidden\" name=\"ud_id\" value=\"$id\">
                  <input type=\"submit\" value=\"Update Story\" name=\"cmdSubmi t\">
                  </td>
                  </tr>
                  ";

                  $m++;

                  } //end of while

                  ?>



                  </table>
                  </td></tr></table>
                  </td></tr></table>

                  </form>


                  <?php include 'footer.php'; ?>
                  [/PHP]

                  Comment

                  • Motoma
                    Recognized Expert Specialist
                    • Jan 2007
                    • 3236

                    #10
                    Try doing a little debugging!
                    Craft in a couple of echo statements, before and after the str_replace();
                    Are you getting to the code after it, or is the script halting?
                    What is the content of $body before and after?
                    $restored_strin g?
                    Do you have errors on? Do you get any messages when you do?

                    Comment

                    • cheezylu
                      New Member
                      • Feb 2007
                      • 6

                      #11
                      I am a complete idiot. I was putting the code outside my while loop! Eeesh!

                      Thank you very much for all of your patience. I had been working on all of this for two whole days with very little sleep. I guess I have learned my lesson that sleep, while time consuming, is quite useful. Thanks again!

                      Comment

                      • Motoma
                        Recognized Expert Specialist
                        • Jan 2007
                        • 3236

                        #12
                        Originally posted by cheezylu
                        I am a complete idiot. I was putting the code outside my while loop! Eeesh!

                        Thank you very much for all of your patience. I had been working on all of this for two whole days with very little sleep. I guess I have learned my lesson that sleep, while time consuming, is quite useful. Thanks again!
                        Glad you got it all figured out, and welcome to The Scripts!

                        Comment

                        Working...