note 96340 added to function.nl2br
| From: | kanon11removethis at alsoremove dot yahoo dot com | Date: | Mon, 22 Feb 2010 06:18:52 +0000 |
| Subject: | note 96340 added to function.nl2br | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-166242@lists.php.net to get a copy of this message | ||
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;
}
?>
----
Server IP: 69.147.83.197
Probable Submitter: 66.243.195.169
----
Manual Page -- http://www.php.net/manual/en/function.nl2br.php
Edit -- https://master.php.net/note/edit/96340
Del: integrated -- https://master.php.net/note/delete/96340/integrated
Del: useless -- https://master.php.net/note/delete/96340/useless
Del: bad code -- https://master.php.net/note/delete/96340/bad+code
Del: spam -- https://master.php.net/note/delete/96340/spam
Del: non-english -- https://master.php.net/note/delete/96340/non-english
Del: in docs -- https://master.php.net/note/delete/96340/in+docs
Del: other reasons-- https://master.php.net/note/delete/96340
Reject -- https://master.php.net/note/reject/96340
Search -- https://master.php.net/manage/user-notes.php