Jump to content

[SOLVED] how to use preg_replace()


andz

Recommended Posts

how do i use this preg_replace() to validate content.

 

$content = 'testingmike123<script>alert("test")</script>';

 

how do validate that the system wont execute the <script></script> using preg_replace();

 

Thanks

Link to comment
Share on other sites

I assume you want to remove the script,

try this (remove)

$content = preg_replace('%<script.*?>.*?</script>%sim', '', $content );

keep the script but kill the tags

$content = preg_replace('%<script.*?>(.*?)</script>%s', '\1', $content );

 

 

Link to comment
Share on other sites

@MadTechie:

 

Thanks for the solution mate.

 

I used this solution of yours ::

 

$content = preg_replace('%<script.*?>.*?</script>%sim', '', $content );

 

how about if i have multiple tags on the $content, example

 

$content = 'mymessage<script>alert("test")</script><embed>source</embed>';

 

how do i add that to validation?

Link to comment
Share on other sites

use htmlspecialchars

ie

$content = htmlspecialchars($content, ENT_QUOTES);

 

or even try this

$content = 'my <b>message</b><script>alert("test")</script> <embed>source</embed>';
$content = preg_replace('%<([^>]*)>(.*?)</\1>%sim', '\2', $content);
$content = htmlspecialchars($content, ENT_QUOTES);
echo $content;

Link to comment
Share on other sites

i'd like to but to the script that I'm working, applying htmlspecialchars() is not an options as some of the scripts will not function.

 

i already tried applying it, although it worked but some pages suffered.

 

i wanted to validate the <script></script> and <embed></embed> tags

 

how do i put it into action considering this example below?

 

 

$content = 'mymessage<script>alert("test")</script><embed>source</embed>';

 

 

thank you very much

Link to comment
Share on other sites

ok this removes embed and script

//simple
$content = preg_replace('%<(script|embed)[^>]*>(.*?)</\1>%s', '\2', $content );

//try this
$remove = array('script','embed');
$remove = implode("|", $remove);
$content = preg_replace('%<('.$remove.')[^>]*>(.*?)</\1>%s', '\2', $content );

Link to comment
Share on other sites

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.