Rewriting eregi_replace to preg_replace

Hi All,

I’m having some problems converting my eregi_replace to preg_replace too.

I’m removing content in a <div> from my page using eregi_replace before this and it is working fine:

$print[1] = eregi_replace("<div id=\\"countdown\\">(.*)<div id=\\"rightcontent\\">", "<div id=\\"rightcontent\\">",$print[1]);

However, as my host upgraded to PHP 5.3, I get eregi is deprecated warning. I tried to convert my script to preg_replace like below but it is not working:

$print[1] = preg_replace("~<div id=\\"countdown\\">(.*)<div id=\\"rightcontent\\">~Ui", "<div id=\\"rightcontent\\">",$print[1]);	

Can anyone please tell me where’s my error?

Appreciate for your sharing.

Thanks!

@liyenn, presuming that the two div tags you’re searching are on different lines, then you’ll need to use the s pattern modifier.


$print[1] = preg_replace('~<div id="countdown">(.*)<div id="rightcontent">~Uis', '<div id="rightcontent">',$print[1]);
#by using single quotes to surround our expression and replacement pattern, we no longer have to escape every double quote inside.

Running the above code on:


<div id="countdown">test
<div id="rightcontent">
test
</div></div>
<div id="countdown">test
<div id="rightcontent">
test
</div></div>

Will produce the following:


<div id="rightcontent">
test
</div></div>
<div id="rightcontent">
test
</div></div>

However as you can see, we are left with an overhang of closing div tags, so perhaps you should try the following regular expression:


preg_replace('~<div id="countdown">(.*)<div id="rightcontent">(.*)</div>(.*)</div>~Uis', '<div id="rightcontent">\\2</div>', $string);

The above will turn the following:


<div id="countdown">test
<div id="rightcontent">
test
</div></div>
<div id="countdown">test
<div id="rightcontent">
test
</div></div>

Into this:


<div id="rightcontent">test
</div>
<div id="rightcontent">test
</div>