2

我需要学习如何使用 PHP 删除 html 标签。

这就是我的想法(我认为 DOM 措辞是我需要的,但我不知道它是如何工作的。一个工作示例对我有很大帮助。我无法安装任何外部库,我正在运行 PHP 5 ):

function the_remove_function($remove){

//  dom parser code here?

return $remove;}

// return all content into a string
ob_start('the_remove_function');

示例代码:

<body>
<div class="a"></div>
<div id="b"><p class="c">Here are some text and HTML</p></div>
<div id="d"></div>
</body>

问题:

1)如何退货:

<body>
<p class="c">Here are some text and HTML</p>
</body>

2)如何退货:

<body>
<div class="a"></div>
<div id="b"></div>
<div id="d"></div>
</body>

3) 我如何退货:

<body>
<div class="a"></div>
<p class="c">Here are some text and HTML</p>
<div id="d"></div>
</body>

下一个示例代码:

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel='stylesheet' id='test-css'  href='http://www.domain.com/css/test.css?ver=2011' type='text/css' media='all' />
<script type='text/javascript' src='http://www.domain.com/js/test.js?ver=2010123'></script>
</head>

4) 我如何退货:

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel='stylesheet' id='test-css'  href='http://www.domain.com/css/test.css?ver=2011' type='text/css' media='all' />
</head>

5) 我如何退货:

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type='text/javascript' src='http://www.domain.com/js/test.js?ver=2010123'></script>
</head>

谢谢阅读 :)

4

3 回答 3

2

试试HTML Purifier库。它完全满足您的需求,并提供有关如何创建过滤器的大量文档。如果你因为安全原因想要过滤,那么一定要使用它——它有一个解析器,可以处理可以想象的最疯狂的 XSS 方案。

于 2011-04-10T13:29:29.547 回答
1

尝试使用:

strip_tags();

php中的函数。

样品用法

    <?php
    $str = '<body>
            <div class="a"></div>
            <div id="b"><p class="c">Here are some text and HTML</p></div>
            <div id="d"></div>
            </body>
           ';
    echo strip_tags($str);
    echo "\n";
    ?>

它会返回:

Here are some text and HTML 

    <?php
     $str = '<body>
             <div class="a"></div>
             <div id="b"><p class="c">Here are some text and HTML</p></div>
             <div id="d"></div>
             </body>
            ';
     echo strip_tags($str, '<body>');
     echo "\n";
    ?>

这将允许 ' <body>' 标记并删除另一个标记。结果 :

<body>
Here are some text and HTML
</body>

更多示例 Php.Net

于 2011-04-10T09:47:03.943 回答
1

您可以使用 PHP 的所有 DOM 类,您将在此处查看文档:http: //fr2.php.net/manual/en/book.dom.php,我相信您可以找到很多您喜欢的教程.

这是您的第二种情况的示例:

<?php
$content = '<body><div class="a"></div><div id="b"><p class="c">Here are some text and HTML</p></div><div id="d"></div></body>';
$doc = new DOMDocument();
$doc->loadXML($content);

//Get your p element
$p = $doc->getElementsByTagName('p')->item(0);
//Remove the p tag from the DOM
$p->parentNode->removeChild($p);

//Save you new DOM tree
$html = $doc->saveXML();

echo $html;
//If you want to delete the first line
echo substr($html, strpos($html, "\n"));
于 2011-04-10T09:48:41.667 回答