tags:

views:

299

answers:

2

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

Thanks.

+1  A: 
$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>

Erik
A: 

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

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

which, for your example, results in:

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

GreenMatt