Dom*_*oSL 9 html php scripting bots
我需要一个PHP脚本,它接受一个网页的URL,然后回显一个单词被提到的次数.
这是一个通用的HTML页面:
<html>
<body>
<h1> This is the title </h1>
<p> some description text here, <b>this</b> is a word. </p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
这将是PHP脚本:
<?php
htmlurl="generichtml.com";
the script here
echo(result);
?>
Run Code Online (Sandbox Code Playgroud)
所以输出将是这样的表:
WORDS Mentions
This 2
is 2
the 1
title 1
some 1
description 1
text 1
a 1
word 1
Run Code Online (Sandbox Code Playgroud)
这就像搜索机器人在网上冲浪时所做的那样,所以,任何想法如何开始,甚至更好,你有一个PHP脚本已经这样做了吗?
Pet*_*tai 25
从字符串中删除所有HTML标记后,下面的一行将执行不区分大小写的字数.
print_r(array_count_values(str_word_count(strip_tags(strtolower($str)), 1)));
Run Code Online (Sandbox Code Playgroud)
要获取页面的源代码,您可以使用cURL或file_get_contents()
$str = file_get_contents('http://www.example.com/');
Run Code Online (Sandbox Code Playgroud)
从内到外:
1 返回一个数组,其中包含在字符串中找到的所有单词.下面的脚本将读取远程URL的内容,删除html标记,并计算其中每个唯一单词的出现次数.
警告:在您的预期输出中,"This"的值为2,但下面区分大小写,因此"this"和"This"都记录为单独的单词.如果原始案例对您的目的不重要,您可以在处理之前将整个输入字符串转换为小写字母.
此外,由于仅在输入上运行基本的strip_tags,因此不会删除格式错误的标记,因此假设您的源html有效.
编辑:查理在评论中指出,该head部分之类的内容仍将被计算在内.借助strip_tags函数的用户注释中定义的函数,现在也可以使用这些函数.
generichtml.com
<html>
<body>
<h1> This is the title </h1>
<p> some description text here, <b>this</b> is a word. </p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
?>
输出:
Array
(
[This] => 1
[is] => 2
[the] => 1
[title] => 1
[some] => 1
[description] => 1
[text] => 1
[here] => 1
[this] => 1
[a] => 1
[word] => 1
)
Run Code Online (Sandbox Code Playgroud)