下面的脚本会读取远程 url 的内容,去除 html 标签,并统计其中每个唯一单词的出现次数。
警告:在您的预期输出中,“This”的值为 2,但下面的内容区分大小写,因此“this”和“This”都被记录为单独的单词。如果原始大小写对您的目的不重要,您可以在处理之前将整个输入字符串转换为小写。
此外,由于只对输入运行基本的 strip_tags,格式错误的标签不会被删除,因此假设您的源 html 是有效的。
编辑: Charlie 在 cmets 中指出,head 部分之类的内容仍将被计算在内。在user notes of the strip_tags function 中定义的函数的帮助下,这些现在也得到了处理。
generichtml.com
<html>
<body>
<h1> This is the title </h1>
<p> some description text here, <b>this</b> is a word. </p>
</body>
</html>
parser.php
// Fetch remote html
$contents = file_get_contents($htmlurl);
// Get rid of style, script etc
$search = array('@<script[^>]*?>.*?</script>@si', // Strip out javascript
'@<head>.*?</head>@siU', // Lose the head section
'@<style[^>]*?>.*?</style>@siU', // Strip style tags properly
'@<![\s\S]*?--[ \t\n\r]*>@' // Strip multi-line comments including CDATA
);
$contents = preg_replace($search, '', $contents);
$result = array_count_values(
str_word_count(
strip_tags($contents), 1
)
);
print_r($result);
?>
输出:
Array
(
[This] => 1
[is] => 2
[the] => 1
[title] => 1
[some] => 1
[description] => 1
[text] => 1
[here] => 1
[this] => 1
[a] => 1
[word] => 1
)