Search code examples
phpstrip-tags

php strip_tags, allow PHP tags?


I found a lot of topics asking to keep some html tags but I didn't find any which wanted to keep the php tags !

I want something like this :

$myString = '<i> Hello, my name is <?php echo $firstName ?> and I'm <?php echo $age ?> </i> <div> my other div content </div>';
$myBeautifulString = strip_tags($myString, '<?php');

and the result I would :

var_dump($myBeautifulString);
==> 
'Hello, my name is <?php echo $firstName ?> and I'm <?php echo $age ?> my other div content'

I need to put the content of this string into a file so I absolutely need to keep the php tags ! The values to fill will be given only after.


Solution

  • From the manual:

    Note:

    HTML comments and PHP tags are also stripped. This is hardcoded and can not be changed with allowable_tags.

    (My emphesis)

    You claim to have read the manual but seem not to have noticed this important caveat. So your solution to retain <?php ... ?> within your string is to not use strip_tags function at all and to make your own function with a custom list of tags to remove.

    (Basic example only):

    function my_strip_tags(string $string, array $tags){
         $outputString = $string;
         foreach($tags as $tag){
             $outputString = str_ireplace($tag, '', $outputString);
         }
         unset($tag);
         return $outputString;
    }