Page 1 of 1

php/mysql insert CR before dd/mm/yyyy in string

Posted: Mon Jul 02, 2012 12:12 pm
by cjkeane
Hi everyone.

I'm wondering if anyone could suggest a solution to a problem i'm having. In a mysql db, i have a longtext datatype field with data such as:
"07/15/2008 this is a test 07/14/2008 this is a second test"

When I display the data on a page using the coding below, the text appears in a single line. I need a line break to occur before each date within the History field. Is this possible? Any help would be appreciated. Thanks.

Code: Select all

 <?php
        $ID = $_GET['ID'];
        $result = mysql_query("SELECT ID, History FROM HistoryTable WHERE ID='$ID'") or die(mysql_error());     
        echo "<table border='0' cellpadding='1'>";
        echo "<tr>";
        while($row = mysql_fetch_array( $result )) {
                echo "<tr>";
		echo '<td>' . nl2br($row['History']) . '</td>';
                echo "</tr>"; 
        } 
        echo "</table>";
?>

Re: php/mysql insert line breaks

Posted: Mon Jul 02, 2012 2:17 pm
by tr0gd0rr
Maybe you need to replace using a regular expression? Maybe like

Code: Select all

preg_replace('/\d\d\//', '<br>$0', $row['History'])

Re: php/mysql insert line breaks

Posted: Mon Jul 02, 2012 3:13 pm
by mikosiko
"07/15/2008 this is a test 07/14/2008 this is a second test"
any reason to store the information in that way?... seems that you are trying to store several "records" in just one field.... no good at all... every date/message should be a different record in your table history

Re: php/mysql insert line breaks

Posted: Mon Jul 02, 2012 6:48 pm
by cjkeane
its stored like that because it was imported from another db type into mysql and the line breaks were omitted, so i need to force a line break before each date using php. i would have imported the data into two fields, date and history, but it was no possible to separate the data during the import process.

Re: php/mysql insert line breaks

Posted: Mon Jul 02, 2012 7:47 pm
by cjkeane
tr0gd0rr wrote:Maybe you need to replace using a regular expression? Maybe like

Code: Select all

preg_replace('/\d\d\//', '<br>$0', $row['History'])
in using the above, the data is displayed as below.

01/
08/2007 test message one
01/
04/2007 test message two

how can this be fixed so that it displays like this:

01/08/2007 test message one
01/04/2007 test message two

Re: php/mysql insert CR before dd/mm/yyyy in string

Posted: Mon Jul 09, 2012 2:16 pm
by tr0gd0rr
Sorry, the regex needs a space before the \d

Code: Select all

preg_replace('/ (\d\d\/)/', '<br>$1', $row['History']);

Re: php/mysql insert CR before dd/mm/yyyy in string

Posted: Mon Jul 09, 2012 2:31 pm
by cjkeane
great! thanks. I got it to work.