note 62684 added to function.preg-replace

From: Date: Tue, 07 Mar 2006 09:32:23 +0000
Subject: note 62684 added to function.preg-replace
Groups: php.notes 
Request: Send a blank email to php-notes+get-104967@lists.php.net to get a copy of this message
Inspired by the query-string cleaner from greenthumb at 4point-webdesign dot com and istvan dot csiszar at weblab dot hu. This little bit of code cleans up any "style" attributes in your tags, leaving behind only styles that you have specifically allowed. Also conveniently strips out nonsense styles. I've not fully tested it yet so I'm not sure if it'll handle features like url(), but that shouldn't be a difficulty. <?php /* The string would normally be a form-submitted html file or text string */ $string = '<span style="font-family:arial; font-size:20pt; text-decoration:underline; sausage:bueberry;" width="200">Hello there</span> This is some <div style="display:inline;">test text</div>'; /* Array of styles to allow. */ $except = array('font-family', 'text-decoration'); $allow = implode($except, '|'); /* The monster beast regexp. I was up all night trying to figure this one out. */ $regexp = '@([^;"]+)?(?<!'.$allow.'):((.*?)[^;"]+)(;)?@'; print str_replace('<', '&lt', $regexp).'<br/><br/>'; $out = preg_replace($regexp, '', $string); /* Now lets get rid of any unwanted empty style attributes */ $out = preg_replace('@[a-z]*=""@is', '', $out); print $out; ?> This should produce the following: <span style="font-family:arial; text-decoration:underline;" width="200">Hello there</span> This is some <div >test text</div> Now, I'm a relative newbie at this so I'm sure there's a better way to do it. There's *always* a better way. ---- Server IP: 85.116.0.130 Probable Submitter: 86.144.119.249 ---- X-Spam-Status: No, hits=4.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER, HTML_30_40,HTML_MESSAGE autolearn=no version=2.64 ---- Manual Page -- http://www.php.net/manual/en/function.preg-replace.php Edit -- http://master.php.net/note/edit/62684 Del: integrated -- http://master.php.net/note/delete/62684/integrated Del: useless -- http://master.php.net/note/delete/62684/useless Del: bad code -- http://master.php.net/note/delete/62684/bad+code Del: spam -- http://master.php.net/note/delete/62684/spam Del: non-english -- http://master.php.net/note/delete/62684/non-english Del: in docs -- http://master.php.net/note/delete/62684/in+docs Del: other reasons-- http://master.php.net/note/delete/62684 Reject -- http://master.php.net/note/reject/62684 Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#104967) next »