Jump to content

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


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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.