Jump to content

newline convert to <br /> exceptions in HTML text


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>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.