如何修复使用PHP在纯文本中计算单词的错误? - php

多亏了Filestack上的Document Transformations,我可以从.DOC / .DOCX文件中获得文本/纯文本输出。我只想用PHP计算此输出的单词数(没有数字或标点符号),并显示在HTML页面中。所以我有这个:

<button type="button" id="load" class="btn btn-md btn-info">LOAD FILES</button>
<br>
<div id="result"></div>

<script src="../vendors/jquery/dist/jquery.min.js"></script>
<script src="https://static.filestackapi.com/v3/filestack.js"></script>
<script>

    function numWordsR(urlk){ 
        $.post("result_filestack.php",{
            molk: urlk //urlk, example: https://process.filestackapi.com/output=format:txt/AXXXXAXeeeeW33A";
        }).done(function(resp){
            $("#result").html(resp);
        });
    }
</script>

和我的文件result_filestack.php:

$url = $_POST['molk'];
$content = file_get_contents($url); //get txt/plain output content
$onlywords = preg_replace('/[[:punct:]\d]+/', '', $content); //no numbers nor punctuation symbols

function get_num_of_words($string) {
   $string = preg_replace('/\s+/', ' ', trim($string));
   $words = explode(" ", $string);
   return count($words);
}

$numwords = get_num_of_words($onlywords);
echo "<b>TEXT:</b>: ".$onlywords."<br><br>Number of words: ".$numwords;

我得到这个结果:

如何修复使用PHP在纯文本中计算单词的错误? - php

例如,在这种情况下,结果表明文本中有585个单词,但是如果我将该文本复制并粘贴到MS Word中,它将显示612个单词。我更改PHP代码以映射文本数组:

function get_text($string) {
 $string = preg_replace('/\s+/', ' ', trim($string));
 $words = explode(" ", $string);
 return $words;
}

$texto002 = get_text($onlywords);
echo print_r($texto002);

我注意到在计算单词时会出错,在某些情况下,会将两个或三个单词作为一个单词:

如何修复使用PHP在纯文本中计算单词的错误? - php

我该如何解决?

我需要你的帮助。

参考方案

可能是因为空格不是常规空格,而是特殊字符,
经历了一段时间,在爆炸常规空间之前,我用空间替换了实体

function get_num_of_words($string) {
   $string = preg_replace('/\s+/', ' ', trim($string));
   $string = str_replace("&nbsp;", " ", $string);
   $string = str_replace(" ", " ", $string);

   $words = explode(" ", $string);

   return count($words);
}

PHP JQuery复选框 - php

我有以下片段。 var myData = { video: $("input[name='video[]']:checked").serialize(), sinopse: $("#sinopse").val(), dia: $("#dia").val(), quem: $(&#…

将大字符串分成多个小字符串-PHP - php

我从数据库中获取了一个长字符串,我需要对其进行解析,以使其不包含一个大字符串,而是多个,其中每个字符串都有2个字符。让我们以示例为例:我连接到表,获取此字符串:B1C1F4G6H4I7J1J8L5O6P2Q1R6T5U8V1Z5,之后,我必须对字符串进行解析,因此:B1 C1 F4 G6 H4 I7 J1 J8 L5 O6 P2 Q1 R6 T5 U8 V1…

PHP Count数组元素 - php

嗨,有人可以解释为什么这会返回“数组由0个元素组成”。 :$arr = array(1,3,5); $count = count($arr); if ($count = 0) { echo "An array is empty."; } else { echo "An array has $count elements.…

如何从php中获取datatables jQuery插件的json数据 - php

我是PHP的新手,正在尝试使用Datatables jQuery插件。我知道我必须从.php文件中获取数据,然后在数据表中使用它,但是我似乎无法通过ajax将其传递给数据表。我设法从数据库中获取数据,并对其进行json编码,但是后来我不知道如何在我的index.php文件中调用它,并在其中显示它。我究竟做错了什么?这是我的代码:HTML(已编辑): <…

PHP:从函数返回值并直接回显它? - php

这可能是一个愚蠢的问题,但是……的PHPfunction get_info() { $something = "test"; return $something; } html<div class="test"><?php echo get_info(); ?></div> 有没有办…