I say PHP, because I have this snippet to count the words with PHP, maybe it's better with jQuery?
$words = str_word_开发者_如何转开发count(strip_tags($myString));
I have a PHP page with static HTML mixed with some PHP variables like so:
<?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>
I tried looking into PHP's output buffering and slipped an ob_start()
and $buffer = ob_get_clean();
around the .to_count DIV, but I can't seem to use the $buffer
in the top section on the PHP page to count the words.
Any help to set me on the way is appreciated, cheers.
With jQuery and regex:
var wordCount = $.trim($(".to_count").text()).split(/\s+/g).length;
you can't use buffer before it is declared. If you do it will default to a value that isn't useful. I recommend counting the words before inserting them into the HTML and setting a variable with the count.
I recommend building the content of the .to_count div before actually rendering it. Something like this:
<?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>
You could use output buffering to generate it. Which I think is tider than generating HTML in php.
<?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>
精彩评论