Jump to content

newline convert to <br /> exceptions in HTML text


Catfish

Recommended Posts

Hi all,

 

I've got some scripting that pulls data from a database and outputs it in the browser. The way I want it to work is that when a user inputs/edits the data it can handle HTML tags, but when they put a newline (\n) in the data, this will automatically convert to a HTML linebreak tag <br /> upon data output.

 

I have that working fine, but there are some times when I want an exception to the "convert newlines to <br />" rule.

 

Examples of this are:

data between <pre></pre> tags should not convert \n to <br /> and data between <ul></ul> or <ol></ol> tags etc. as the newlines are preformatted in the HTML layout.

 

If I made an array to hold all of the tag pairs that newlines should not be converted between, I could loop it and perhaps use a regex to prevent the conversions - or even convert the <br />s back to \n.

 

Anyone get what I want to do?

Amount of nesting can vary, as everything is dynamic and I want to allow the user as much freedom as possible.

 

Typical data size would be pretty small. I can't give you an exact size though. You'd be looing at about 1 browser page of data at the maximum.

Try this:

 

<pre>
<?php
$data = <<<DATA
<h1>Heading
</h1>
<pre>Pre
</pre>
<ul>
<ol>A
</ol>
<ol>B
</ol>
</ul>
<p>P
</p>
DATA;

### Separate the tags from the data.
$pieces = preg_split('%(<[^>]*>)%', $data, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
foreach ($pieces as $piece) {
	echo htmlspecialchars($piece);
}
echo '<hr>';

### Parse.
$level = 0;
foreach ($pieces as &$piece) {
	echo "($level) ", htmlspecialchars($piece);
	### Determine nesting.
	if (substr($piece, 0, 1) == '<') {
		preg_match('%<(?:pre|[ou]l)[^>]*>%i', $piece) ? ++$level : null ;
		preg_match('%</(?:pre|[ou]l)>%i', $piece) ? --$level : null ;
	}
	### If a level exists, trim trailing white space.
	elseif ($level) {
			$piece = rtrim($piece);
	}
}
unset($piece);
echo '<hr>';
foreach ($pieces as $piece) {
	echo htmlspecialchars($piece);
}
?>
</pre>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.