Qiao
Qiao

Reputation: 17049

RegEx (php) - unite lines in multiline replacement

I need change background of all text that have two spaces from the start of the line.

  text

shold be converted to "<div class='special'>text</div>"

That is easy:

$text = preg_replace("|^  (.+)|um", "<div class='special'>$1</div>", $text);

But

  line1
  line2

Is converted to

<div class='special'>line1</div>
<div class='special'>line2</div>

Though

<div class='special'>line1
line2</div>

is needed.

How that can be achieved?

Upvotes: 0

Views: 162

Answers (2)

tiftik
tiftik

Reputation: 988

Replace

((?:^  [^\r\n]*(?:\R(?=  ))?)+)

with <div class='special'>$1</div>.

But this will convert

  line1
  line2

to this:

<div class='special'>  line1
  line2</div>

If you want to remove the spaces, you should match the text, remove the spaces and then replace.

Upvotes: 0

timdev
timdev

Reputation: 62884

You'll want to use the "s" (DOTALL) pattern modifier so you can capture multiple lines. Then stop the greed by matching "newline followed by something other than two spaces"

<?PHP
$text = "
  Line One
  Line Two
  Line Three
something";

$text = preg_replace("|^  (.+)^[^(  )]|ums", "<div class='special'>$1</div>\n", $text);


echo $text;

Outputs:

<div class='special'>Line One
  Line Two
  Line Three
</div>

Upvotes: 1

Related Questions