2011-02-17 53 views
0

我說PHP,因爲我有這個片段來計算PHP的單詞,也許用jQuery更好?PHP:計算DIV中的單詞

$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,但我似乎無法使用PHP頁面頂部的$buffer來計算單詞。

任何幫助設置我的方式是讚賞,歡呼聲。

回答

2

使用jQuery和正則表達式:

var wordCount = $.trim($(".to_count").text()).split(/\s+/g).length; 
+1

我可能會在`.split()`調用之前添加`.trim()`調用,以防萬一有多餘的空格。 Web檢查員的快速測試表明,縮進會被視爲一個單詞。 – 2011-02-17 04:00:26

+0

是的,我正在去jQuery路線,因爲我已經加載了所有需要wordCounts的頁面。謝謝 – FFish 2011-02-17 04:13:36

0

聲明之前,你不能使用緩衝區。如果你這樣做,它將默認爲一個無用的值。我建議在將它們插入HTML並用count設置一個變量之前對這些單詞進行計數。

+0

感謝清除那斯科特。 – FFish 2011-02-17 04:14:24

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> 
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>