0

我说 PHP,因为我有这个片段可以用 PHP 计算单词,也许用 jQuery 更好?

$words = str_word_count(strip_tags($myString));

我有一个带有静态 HTML 的 PHP 页面,其中混合了一些 PHP 变量,如下所示:

<?php 
    $foo = "hello"; 
?>
<html>
<body>
    <div>total words: <?= $words ?></div>
    <div class="to_count">
        <?= $foo ?> <b>big</b> <i>world</i>, how <span>are</span> we today?
    </div>
</body>
</html>

我尝试查看 PHP 的输出缓冲并ob_start()$buffer = ob_get_clean();.to_count DIV 周围滑动,但我似乎无法使用$bufferPHP 页面顶部的字数来计算单词。

感谢任何帮助我上路的帮助,干杯。

4

4 回答 4

2

使用 jQuery 和正则表达式:

var wordCount = $.trim($(".to_count").text()).split(/\s+/g).length;
于 2011-02-17T03:53:59.623 回答
0

在声明之前不能使用缓冲区。如果你这样做,它将默认为一个无用的值。我建议在将单词插入 HTML 之前对单词进行计数,并使用计数设置变量。

于 2011-02-17T03:54:00.393 回答
0

我建议在实际渲染之前构建 .to_count div 的内容。像这样的东西:

<?php 
    $foo = "hello";
    $content = "$foo <b>big</b> <i>world</i>, how <span>are</span> we today?";
    $words = str_word_count(strip_tags($content));
?>
<html>
<body>
    <div>total words: <?= $words ?></div>
    <div class="to_count"><?= $content ?></div>
</body>
</html>
于 2011-02-17T03:58:26.660 回答
0

您可以使用输出缓冲来生成它。我认为这比在 php 中生成 HTML 更潮。

<?php
ob_start();
$foo = "hello";
?>


<?php echo $foo ?> <b>big</b> <i>world</i>, how <span>are</span> we today?

<?php
    $myString = ob_get_contents();
    ob_end_clean();
    $words = str_word_count(strip_tags($myString));
?>
<html>
<body>
    <div>total words: <?php echo $words ?></div>
    <div class="to_count">
        <?php echo $myString ?>
    </div>
</body>
</html>
于 2011-02-17T04:05:09.870 回答