【发布时间】:2020-07-10 14:29:33
【问题描述】:
我正在尝试计算示例字符串中的单词,如下所示:
<p> <p>hello world!</p><p> </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> <p>hello world!</p><p> </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