在 PHP 中计算文章字数可以根据语言类型(中文或英文)采用不同的方法。以下是几种常见的实现方式:
1. 基础方法(区分中英文)
中文文章(按字符计算)
使用函数正确统计中文字符(UTF-8 编码):
mb_strlen()
php
$content = "这是一篇中文文章。";
$wordCount = mb_strlen($content, 'UTF-8');
echo $wordCount; // 输出:9(包括标点符号)
英文文章(按单词计算)
使用正则表达式匹配单词:
php
$content = "";
preg_match_all('/\b\w+\b/', $content, $matches);
$wordCount = count($matches[0]);
echo $wordCount; // 输出:5
2. 自动检测语言并计算字数
结合语言检测和对应的计算方法:
php
function countWords($content) {
// 检测是否包含中文(简单判断)
if (preg_match('/\p{Han}/u', $content)) {
// 中文:按字符统计(包括标点)
return mb_strlen($content, 'UTF-8');
} else {
// 英文:按单词统计
preg_match_all('/\b\w+\b/', $content, $matches);
return count($matches[0]);
// 示例
$cnContent = "你好,世界!";
$enContent = "Hello, world!";
echo countWords($cnContent); // 输出:6(中文字符+标点)
echo countWords($enContent); // 输出:2(单词数)
3. 高级方法(忽略标点符号)
如果需要更精确的统计(如仅统计有效单词或汉字):
中文(仅统计汉字,忽略标点和数字)
php
$content = "你好,世界!123";
preg_match_all('/\p{Han}/u', $content, $matches);
$wordCount = count($matches[0]);
echo $wordCount; // 输出:4(仅“你好世界”)
英文(忽略标点)
php
$content = "This is a test... really!";
$content = preg_replace('/[^\w\s]/', '', $content); // 去除标点
preg_match_all('/\b\w+\b/', $content, $matches);
$wordCount = count($matches[0]);
echo $wordCount; // 输出:4
4. 处理 HTML 内容
如果文章包含 HTML 标签,需要先去除标签再统计:
php
$htmlContent = "";
这是一段加粗的文字。
$text = strip_tags($htmlContent); // 去除HTML标签
$wordCount = mb_strlen($text, 'UTF-8');
echo $wordCount; // 输出:11
5. 完整函数示例
php
* 统计文章字数(支持中英文混合)
* @param string $content 文章内容
* @param bool $ignorePunctuation 是否忽略标点符号
* @return array 返回字数统计结果
function getWordCount($content, $ignorePunctuation = true) {
// 去除HTML标签
$text = strip_tags($content);
// 检测语言并统计
$isChinese = preg_match('/\p{Han}/u', $text);
if ($isChinese) {
// 中文:按字符或汉字统计
if ($ignorePunctuation) {
preg_match_all('/\p{Han}/u', $text, $matches);
$count = count($matches[0]);
} else {
$count = mb_strlen($text, 'UTF-8');
} else {
// 英文:按单词统计
if ($ignorePunctuation) {
$text = preg_replace('/[^\w\s]/', '', $text);
preg_match_all('/\b\w+\b/', $text, $matches);
$count = count($matches[0]);
return [
'total' => $count,
'language' => $isChinese ? 'chinese' : 'english',
'is_html' => ($content !== $text)
// 示例
$article = "";
PHP is great! 编程很有趣。
$result = getWordCount($article);
print_r($result);
// 输出:['total' => 10, 'language' => 'chinese', 'is_html' => true]
关键点总结
- 中文统计:用避免乱码。
- mb_strlen($str, 'UTF-8')
- 英文统计:用正则匹配单词。
- /\b\w+\b/
- 混合内容:通过检测中文字符()自动切换统计方式。
- \p{Han}
- HTML 处理:先用去除标签。
- strip_tags()
- 标点处理:根据需求决定是否忽略。
根据实际需求选择合适的方法即可!
特别声明:以上内容(如有图片或视频亦包括在内)为自媒体平台“网易号”用户上传并发布,本平台仅提供信息存储服务。
Notice: The content above (including the pictures and videos if any) is uploaded and posted by a user of NetEase Hao, which is a social media platform and only provides information storage services.