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?
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>
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.
精彩评论