问题描述
我需要一个PHP脚本,该脚本需要一个网页的URL,然后回显提到一个单词的次数.
I need a PHP script which takes a URL of a web page and then echoes how many times a word is mentioned.
这是通用的HTML页面:
<html>
<body>
<h1> This is the title </h1>
<p> some description text here, <b>this</b> is a word. </p>
</body>
</html>
这将是PHP脚本:
<?php
htmlurl="generichtml.com";
the script here
echo(result);
?>
所以输出将是一个像这样的表:
So the output will be a table like this:
WORDS Mentions
This 2
is 2
the 1
title 1
some 1
description 1
text 1
a 1
word 1
这就像搜索引擎在网上冲浪时所做的一样,因此,关于如何开始甚至更好的任何想法,您是否已经拥有一个可以执行此操作的PHP脚本?
This is something like the search bots do when they are surfing the web, so, any idea of how to begin, or even better, do you have a PHP script which already does this?
推荐答案
在从字符串中删除所有HTML标记后,以下一行将进行不区分大小写的单词计数.
The one line below will do a case insensitive word count after stripping all HTML tags from your string.
print_r(array_count_values(str_word_count(strip_tags(strtolower($str)), 1)));
要获取页面的源代码,可以使用 cURL 或 file_get_contents()
To grab the source code of a page you can use cURL or file_get_contents()
$str = file_get_contents('http://www.example.com/');
由内而外:
- 使用 strtolower() 来完成所有操作小写.
- 使用 strip_tags() 标记HTML标记a>
- 使用 str_word_count() .参数
1
返回一个数组,其中包含在字符串中找到的所有单词. - 使用 array_count_values() 通过计算单词数组中每个值的出现来捕获多次使用的单词.
- 使用 print_r() 来显示结果.
- Use strtolower() to make everything lower case.
- Strip HTML tags using strip_tags()
- Create an array of words used using str_word_count(). The argument
1
returns an array containing all the words found inside the string. - Use array_count_values() to capture words used more than once by counting the occurrence of each value in your array of words.
- Use print_r() to display the results.
这篇关于使用php计数html网页上的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!