tags:

views:

45

answers:

2

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?

+1  A: 

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>
timdev
Your regex fails at many cases. (.+) will make it match anything after two spaces as long as it ends with a "newline followed by something other than two spaces".
tiftik
While I was shooting from the hip, I think that's exactly what Qiao is asking for. How are you reading the requirement?
timdev
"change background of all text that have two spaces from the start of the line". Well, your solution changes lines that don't start with two spaces in this case: " asdf\n1234\n5678".
tiftik
Oh, duh. Yeah....
timdev
A: 

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.

tiftik