Take the 2-minute tour ×

Is it possible to replace newlines with the <br> tag, but to ignore newlines that follow a </h1> tag?

So for example I want to change this block:

<h1>Test</h1> \n some test here \n and here

To this:

<h1>Test</h1> some test here <br /> and here
share|improve this question
Why would you have that kind of code at the first place? It just seems that your orginal situation itself is a problematic. –  newbie Mar 5 '10 at 22:17
add comment

2 Answers

up vote 1 down vote accepted
$subject = "<h1>hithere</h1>\nbut this other\nnewline should be replaced.";
$new = preg_replace("/(?<!h1\>)\n/","<br/>",$subject);
echo $new;

// results in:
// <h1>hithere</h1>
// but this other<br/>newline should be replaced.

Should work. This says \n not preceeded immediately by h1>

share|improve this answer
add comment

Using string functions instead of regular expressions, and assuming the </h1> tag can be anywhere on the line (instead of just before the newline):

foreach ($lines as $line) {
  if (stristr("$line", "</h1>") == FALSE) {
    $line = str_replace("\n", "<br />", $line);
  echo $line;

which, for your example, results in:

some test here <br />and here<br />

share|improve this answer
add comment

Your Answer


