因此,我正在制作一个脚本来根据用户提交的 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";
}
}
我为此编写了两个函数:
/**
* 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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)