【问题标题】:Filtering javascript from site content PHP从网站内容 PHP 中过滤 javascript
【发布时间】:2014-10-21 15:23:51
【问题描述】:

所以我正在制作一个脚本来根据用户提交的 URL 检查页面的关键字密度,并且我一直在使用 strip_tags 但它似乎并没有完全从实际单词中过滤 javascript 和其他代码网站上的内容。有没有更好的方法在页面上的代码内容和实际单词内容之间进行过滤?

if(isset($_POST['url'])){
$url = $_POST['url'];
$str = strip_tags(file_get_contents($url));
$words      = str_word_count(strtolower($str),1);
$word_count = array_count_values($words);

foreach ($word_count as $key=>$val) {
    $density = ($val/count($words))*100;
        echo "$key - COUNT: $val, DENSITY: ".number_format($density,2)."%<br/>\n";
}
}

【问题讨论】:

  • 什么不是剥离?
  • gettime - COUNT: 1, DENSITY: 0.06% event - COUNT: 1, DENSITY: 0.06% js' - COUNT: 1, DENSITY: 0.06% var - COUNT: 2, DENSITY: 0.12% f - 计数:3,密度:0.18% getelementsbytagname - 计数:1,密度:0.06%
  • ^一些不应该出现的东西的例子
  • 这些不是标签,它们是标签之间的 Javascript 的一部分。
  • 我怎样才能从我的字符串中去除 javascript?

标签: javascript php jquery html keyword


【解决方案1】:

我为此编写了 2 个函数:

/**
 * Removes all Tags provided from an Html string
 *
 * @param string   $str    The Html String
 * @param string[] $tagArr An Array with all Tag Names to be removed
 *
 * @return string The Html String without the tags
 */
function removeTags($str, $tagArr)
{
    foreach ($tagArr as $tag) {
        $str = preg_replace('#<' . $tag . '(.*?)>(.*?)</' . $tag . '>#is', '', $str);
    }
    return $str;
}

/**
 * cleans some html string
 *
 * @param string $str some html string
 *
 * @return string the cleaned string
 */
function filterHtml($str)
{
    //Remove Tags
    $str = removeTags($str, ['script', 'style']);

    //Remove all Tags, but not the Content
    $str = preg_replace('/<[^>]*>/', ' ', $str);

    //Remove Linebreaks and Tabs
    $str = str_replace(["\n", "\t", "\r"], ' ', $str);

    //Remove Double Whitespace
    while (strpos($str, '  ') !== false) {
        $str = str_replace('  ', ' ', $str);
    }

    //Return trimmed
    return trim($str);
}

工作示例

$fileContent     = file_get_contents('http://stackoverflow.com/questions/25537377/filtering-html-from-site-content-php');
$filteredContent = filterHtml($fileContent);
var_dump($filteredContent);

【讨论】:

  • 还是黑屏,不知道是什么问题
  • @mako 我改进了不显示脚本标签和不需要空格的方法。我还添加了一个工作示例。如果您使用它,请验证您的代码是否被真正调用。
  • 似乎去掉了我看到的大部分 javascript
  • @mako,自从你更新了问题,我提供了第二个功能,它可以通过黑名单删除所有想要的标签。
【解决方案2】:

您需要解析 HTML,以便拥有类似 DOM 的结构,您可以迭代并访问不同节点的内容。

您可以使用PHP Simple HTML DOM Parser

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    • 1970-01-01
    相关资源
    最近更新 更多