note 96340 deleted from function.nl2br by thiago
| From: | thiago@php.net | Date: | Mon, 22 Feb 2010 06:20:56 +0000 |
| Subject: | note 96340 deleted from function.nl2br by thiago | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-166243@lists.php.net to get a copy of this message | ||
Note Submitter: kanon11removethis at alsoremove dot yahoo dot com
----
I needed the below nl2brPre function, but I also wanted it to not put the <br />'s inside
a <table>.
For example, the following code:
<table>
<tr>
<td>Cell 1</td>
<tr>
</table>
Should NOT become:
<table><br />
<tr><br />
<td>Cell 1</td><br />
<tr><br />
</table><br />
Eric's code below doesn't work, but he has the right idea for properly checking the return
value of strpos. I didn't include his fix for the <p> tag, since textarea input might not
be in a <p> tag.
I also added strtolower() when performing the strpos checks, because some users might not be using
lower-case. I could've used stripos() but then this function wouldn't work in PHP4.
<?php
function nl2brPreTab($string)
{
// First, check for <pre> and <table> tags
if((strpos(strtolower($string), "<pre>") === false) &&
(strpos(strtolower($string), "<table>") === false))
{
return nl2br($string);
}
// If there is a <pre> or <table>, we have to split by line
// and manually replace the linebreaks with <br />
$strArr=explode("\n", $string);
$output="";
$preFound=false;
$tableFound=false;
// Loop over each line
foreach($strArr as $line) {
// See if the line has a <pre>. If it does, set $preFound to true
if(strpos(strtolower($line), "<pre>") !== false)
{
$preFound=true;
}
elseif(strpos(strtolower($line), "</pre>") !== false)
{
$preFound=false;
}
// See if the line has a <table>. If it does, set $tableFound to true
if(strpos(strtolower($line), "<table>") !== false)
{
$tableFound=true;
}
elseif(strpos(strtolower($line), "</table>") !== false)
{
$tableFound=false;
}
// If we are in a pre or table tag, just give a \n, else a <br />
if($preFound || $tableFound)
{
$output .= $line . "\n";
}
else
{
$output .= $line . "<br />";
}
}
return $output;
}
?>