【问题标题】:counting words in a string with html tag in php在php中使用html标签计算字符串中的单词
【发布时间】:2020-07-10 14:29:33
【问题描述】:

我正在尝试计算示例字符串中的单词,如下所示:

<p>&nbsp;<p>hello world!</p><p>&nbsp;</p></p>

阅读文档后,我发现了一个功能,它应该完全符合我的要求。但不知何故,结果并不完全正确。

这是我正在使用的代码:

function rip_tags($string) {

    // ----- remove HTML TAGs -----
    $string = preg_replace ('/<[^>]*>/', ' ', $string);

    // ----- remove control characters -----
    $string = str_replace("\r", '', $string);    // --- replace with empty space
    $string = str_replace("\n", ' ', $string);   // --- replace with space
    $string = str_replace("\t", ' ', $string);   // --- replace with space

    // ----- remove multiple spaces -----
    $string = trim(preg_replace('/ {2,}/', ' ', $string));

    return $string; 
}
$str = '<p>&nbsp;<p>hello world!</p><p>&nbsp;</p></p>';
$str = trim(html_entity_decode($str));
$str = rip_tags($str);
$c = str_word_count($str);
echo $c;

结果应该是 2,但代码返回 4.. 我错过了什么??

【问题讨论】:

  • 我得到 2:ideone.com/kbhfsq
  • 首先使用 HTML 到文本的转换工具,就像他们在这里描述的那样:stackoverflow.com/questions/1884550/… 之后,其余的应该很容易。
  • 首先无效的 HTML 可能无济于事。 (或者我正在阅读不应该有嵌套的地方。)

标签: php string word-count


【解决方案1】:

用以下方式试试你的里程数。

剥离 html,解码实体,然后计算单词。

<?php

$html =<<<HTML
<p>&nbsp;<p>hello world!</p><p>&nbsp;</p></p>
HTML;

$stripped = strip_tags($html);
$decoded  = html_entity_decode($stripped);
echo str_word_count($decoded);

输出:

2

【讨论】:

    【解决方案2】:

    您的函数仍然计算您的 &nbsp,您可以通过以下方式查看:

    $c = str_word_count($str,1);
    var_dump($c);
    

    如果您使用 html_entity_decode() 删除您的 &nbsp,您将看到正确的计数。 (html_entity_decode 只是将相应的 html 实体转换为它们所代表的字符,在您的情况下为空格。)

    $string = html_entity_decode($string);

    【讨论】:

    • 这是问题之一。我已经在使用html_entity_decode 但不知何故&amp;nbsp; 仍然存在..
    • 对不起,我忽略了你的第二部分。我只是复制粘贴了您的代码,它在我的本地机器上运行良好(返回 2)。尝试执行 str_word_count($str,1) 而不是 str_word_count($str) 和 var_dump 你的结果,所以你/我们知道你的字符串实际上是什么样的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    相关资源
    最近更新 更多