php strip_tags,允许 PHP 标签?

php strip_tags, allow PHP tags?

我发现很多主题要求保留一些 html 标签,但我没有找到任何想要保留 php 标签的主题!

我想要这样的东西:

$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');

我想要的结果:

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

我需要将这个字符串的内容放入一个文件中,所以我绝对需要保留 php 标签!要填充的值将仅在之后给出。

为什么不连接字符串呢?

$myString = "Hello, my name is " .$firstName. " and i'm ".$age. "</i>";

strip_tags的第二个参数指定允许的标签。所有其他标签都将被删除。

访问https://www.w3schools.com/php/func_string_strip_tags.asp了解更多信息

您没有添加 , 来分隔两个参数

   <?php
   echo $myString = "<i> Hello, my name is {$firstName} and I\'m {$age} </i> <div> my other div content </div>";

    ?>

如果你有一个包含在单引号中的字符串,并且使用单引号作为字符串的一部分,那么它会破坏你的字符串,所以像这样转义你的字符串 I\'m

删除起始单码并将字符串包含在双码内,如下所示,

echo $myString = "<i> Hello, my name is $firstName and I'm  $age  </i> <div> my other div content </div>";

运行 code

来自the manual

Note:

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

(我的重点)

您声称已阅读手册,但似乎没有注意到这一重要警告。因此,在字符串中保留 <?php ... ?> 的解决方案是根本不使用 strip_tags 函数,并使用要删除的自定义标签列表创建自己的函数。

(仅基本示例):

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

我用 token_get_allstr_replace 来做到这一点:

<?php

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

function remove_html_tag($input)
{
  $to_return = $input;
  $tokens = token_get_all($input);
  foreach ($tokens as $token) {
    if (token_name($token[0]) == 'T_INLINE_HTML') {
      $to_return = str_replace($token[1], strip_tags($token[1]), $to_return);
    }
  }
  return $to_return;
}

function strip_html($input)
{
  return filter_var($input, FILTER_CALLBACK, ['options' => 'remove_html_tag']);
}

var_dump(strip_html($myString));

输出:

string(94) " Hello, my name is <?php echo $firstName ?> and I'm <?php echo $age ?>   my other div content "

演示:https://eval.in/823595

参考文献: