How to replace text over multiple lines using preg_replace

Viewed 33430

Hi have the following content within an html page that stretches multiple lines

<div class="c-fc c-bc" id="content">
                <span class="content-heading c-hc">Heading 1 </span><br />
                The Home Page must provide a introduction to the services provided.<br />
                <br />
                <span class="c-sc">Sub Heading</span><br />
                The Home Page must provide a introduction to the services provided.<br />
                <br />
                <span class="c-sc">Sub Heading</span><br /> 
                The Home Page must provide a introduction to the services provided.<br />
            </div>

I need to replace everthing between <div class="c-fc c-bc" id="content"> and </div> with custom text

I use the following code to accomplish this but it does not want to work if it's multiple lines, but works if evertinh is in one line

$body = file_get_contents('../../templates/'.$val['url']);

$body = preg_replace('/<div class=\"c\-fc c\-bc\" id=\"content\">(.*)<\/div>/','<div class="c-fc c-bc" id="content">abc</div>',$body);

Am I missing something?

5 Answers

If this weren't HTML, I'd tell you to use the DOTALL modifier to change the meaning of . from 'match everything except new line' to 'match everything':

preg_replace('/(.*)<\/div>/s','abc',$body);

But this is HTML, so use an HTML parser instead.

it is the "s" flag, it enables . to capture newlines

How would it be possible to replace text between nested tags, like that:

$sExample2 = "Test [DIV]again[/DIV]
d[COLOR=rgb(184, 49, 47)][SIZE=26px][B][U]o[/U][/B][/SIZE][/COLOR]ssed

This is not [DIV]true[/DIV] !

Yes it is [DIV]true [DIV]but[/DIV] just [/DIV] in that case!.

Why not [DIV]now

?[/DIV] Right here.

Because it is [DIV]down
[DIV]to the [/DIV][/DIV] botton.

I know but i want to [DIV]fly
[DIV]far[/DIV]
[/DIV] away.

";

I want to replace each DIV tuples with * Help *, so that the result looks like

Test ** Test **
d[COLOR=rgb(184, 49, 47)][SIZE=26px][B][U]o[/U][/B][/SIZE][/COLOR]ssed

This is not ** Test ** !

Yes it is ** Test ** in that case!.

Why not ** Test **
 Right here.

Because it is ** Test ** 
botton.

I know but i want to ** Test **
 away.

I tried different replacements, but never received such a result.

print_r(preg_replace(
            '#\[' . preg_quote('DIV', '#') . '](.*?)\[\/' . preg_quote('DIV', '#') . '\]#si',
            '*** Test ***',
            $sExample2
        ));

This one was nearly the best but not what I need.

Related