Jump to content

[SOLVED] Doing a preg_replace on part of a document.


naffets77

Recommended Posts

 

I am given an html document and I needa regular expression to replace every instance of <br /> with \n , but only inside the tags <xmp> and </xmp>.

 

I was using

$content = str_replace("<br />", "\n", $content);

 

but obviously that does it across the entire document.. which is no good.

 

I don't know how to specify only part of a document, w/out replacing the entire tag..

 

$content = preg_replace("/<xmp>.*(<br \/>).*<\/xmp>/", "\n",$content);

 

.. which obviously doesn't work the way i want it to but i think it's a step in the right direction?.

 

Perhaps there is a better way to go about this? I could pull the string out, and then do the replacement and put it back in .. but it's possible that there are a number of these occurring in a document. So I'd have to store it in an array and keep track of where to put it back etc.. i figure doing the preg_replace is the easiest option once i've got the expression down?

 

Thanks for any suggestions.

 

Making assumptions like replacing exactly <br /> with \n inside the tag <xmp>...</xmp>:

 

$str = 'xxx <xmp>This is a test <br /> More tests to come...</xmp> xxx <br /> xxx <xmp> And yet, more tests.. <br /> again!</xmp> xxx.';
$str = preg_replace_callback('#<xmp>.+?</xmp>#si', create_function('$value', 'return(str_replace("<br />", "\n", $value[0]));'), $str);
echo $str;

 

But again, this makes rigid assumptions.. I'm just going by what you mentioned.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.