AtaurRehman Asad
AtaurRehman Asad

Reputation: 173

PHP - Only Removing PHP tag from the string

I have a CMS where I let the user to upload JS and HTML code and I want them use all possible HTML tags, and only tags I want to restrict are <PHP ?> and <? ?>

I know we have strip_tags but it only have the option of allow tags. I want something similar but with the option of ban tags.

Thanks

Upvotes: 0

Views: 102

Answers (4)

Cristiano Casciotti
Cristiano Casciotti

Reputation: 1026

if the tags are only these, you can use preg_replace function:

$string = '<?php content ?>';
$string = preg_replace('/(<\?php|<\?|\?>)/i', '', $string);
echo $string;

it will output content

more information here: http://www.php.net/manual/en/function.preg-replace.php

Upvotes: 1

TiiJ7
TiiJ7

Reputation: 3392

I first want to note that unless you are using eval, this shouldn't really be a problem, but anyway, my solution:

do {
    $content = preg_replace('/(<\\?.*?(\\?>|$))/si', '', $content, -1, $count);
} while($count);

If you're wondering why it's in a loop, it's because hackers can be quite ingenious: <<? ?>?php

This also removes the content between tags.

It will also remove other Processing Instruction tags (like <?xml).

Upvotes: 0

sg3s
sg3s

Reputation: 9567

This can't be done with strip tags as that function only handles html tags, and technically speaking, php open/close tags are not html.

What you could do is use a regular expression for simply matching the strings in context where they could mean something... It's a bit of a broad replace but not a terrible assumption that any tags in this format are meant to be open/close tags and can thus be filtered out:

$result = preg_replace('/<\?php|<\?|\?>/im', '', $content);

Upvotes: 0

Hanky Panky
Hanky Panky

Reputation: 46900

<?php
 $string='this string contains <?php tag';
 $string=str_replace('<?php','',$string);    // same can be done for '?>'
 echo $string;
?>

Demo

Upvotes: 1

Related Questions