Digital
Digital

Reputation: 85

Replace newlines with br but ignore newlines after h1 in PHP

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

Upvotes: 1

Views: 707

Answers (2)

GreenMatt
GreenMatt

Reputation: 18580

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 />

Upvotes: 1

Erik
Erik

Reputation: 20712

$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>

Upvotes: 1

Related Questions