naffets77 Posted August 4, 2009 Share Posted August 4, 2009 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. Link to comment https://forums.phpfreaks.com/topic/168833-solved-doing-a-preg_replace-on-part-of-a-document/ Share on other sites More sharing options...
nrg_alpha Posted August 4, 2009 Share Posted August 4, 2009 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. Link to comment https://forums.phpfreaks.com/topic/168833-solved-doing-a-preg_replace-on-part-of-a-document/#findComment-890788 Share on other sites More sharing options...
naffets77 Posted August 4, 2009 Author Share Posted August 4, 2009 Worked perfectly. The content is coming from a GUI which formats the br's so they should always be <br />. I've never used preg_replace_callback, but now i have a great example. Thanks so much, saved me a ton of time and hassle. Link to comment https://forums.phpfreaks.com/topic/168833-solved-doing-a-preg_replace-on-part-of-a-document/#findComment-890860 Share on other sites More sharing options...
nrg_alpha Posted August 4, 2009 Share Posted August 4, 2009 Perfect Please flag this thread as solved. Link to comment https://forums.phpfreaks.com/topic/168833-solved-doing-a-preg_replace-on-part-of-a-document/#findComment-890876 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.