Forum Moderators: coopster

Message Too Old, No Replies

replacing everything between <code> tags

using preg_replace

         

Warboss Alex

6:18 pm on Aug 14, 2004 (gmt 0)

10+ Year Member



Hey everyone.

I've got a form where people can upload a limited set of html tags, <code> tags included. I want everything between these to be formatted for on-screen display, using htmlspecialchars(), so people can see the source code.

The PHP is:

preg_replace("/<code>(.?)<\/code>/e", "htmlspecialchars($1)", $html); (where $html is the uplodaed html string)

But it's just not replacing anything at all. If I use (.*?) instead of (.?) it just won't parse.

Can anyone help? :(

coopster

2:31 am on Aug 15, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



You didn't try
.*
yet ;)

You may also need to quote that replacement string. And you might want to add a couple more modifiers (case-insensitve and include newlines):

preg_replace("/<code>(.*)<\/code>/eis", "htmlspecialchars('$1')", $html); 

ergophobe

5:26 am on Aug 15, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



You may also want to make the expression ungreedy if you might have multiple occurrences of <code> tags

preg_replace("/<code>(.*)<\/code>/eisU", "htmlspecialchars('$1')", $html);

Warboss Alex

6:37 am on Aug 15, 2004 (gmt 0)

10+ Year Member



Thanks you two! That works great!

But what happens if I wanted to preserve the <code> tags? The preg_replace now removes them..

$html = preg_replace("/<code>(.*)<\/code>/eisU", "<code>htmlspecialchars('$1')</code>", $html); isn't working.. :S

Warboss Alex

3:13 pm on Aug 15, 2004 (gmt 0)

10+ Year Member



Uhh.. anyone?

coopster

10:28 pm on Aug 15, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Just add more subpattern matching:

preg_replace("/(<code>)(.*)(<\/code>)/eis", "'$1' . htmlspecialchars('$2') . '$3'", $string);

Warboss Alex

6:13 am on Aug 16, 2004 (gmt 0)

10+ Year Member



Sorted! Thank you!