开发者

count words within a span tag

I need to count the number of words within the span tag...The text is usually similar to

This<span class="highlight_word"> function is useful to highlight words from a simple non-html </span>text.The<span class="highlight_word"><span class="highlight_word"><span class="highlight_word"> regular expression, as a pattern, can match all kinds of text strings helping your application </span></span>validate, compare, compute, decide etc\. </span>With<span class="highlight_word"><span class="highlight_word"><span class="highlight_word"> the temperature up on keywords and searches, many sites have opted </span></span>for highlighting the keywords from their searches\. This can be useful for quickly finding relavant words withing large pages of text\. </span>

Can anyone guide me a开发者_如何学Gos how to count the number of words within the span tags.

Thanks


On server side, the following counts the words in the span tags in one counter, but you can do this separately for all span elements.

$text = 'This<span class="highlight_word"> function is useful to highlight words from a simple non-html </span>text.The<span class="highlight_word"><span class="highlight_word"><span class="highlight_word"> regular expression, as a pattern, can match all kinds of text strings helping your application </span></span>validate, compare, compute, decide etc\. </span>With<span class="highlight_word"><span class="highlight_word"><span class="highlight_word"> the temperature up on keywords and searches, many sites have opted </span></span>for highlighting the keywords from their searches\. This can be useful for quickly finding relavant words withing large pages of text\. </span>';
$words = 0;
preg_match_all("'span[^>]*[>]([^<]+?)[<]/span'is",$text,$matches);
foreach ($matches[1] as $v)
{
    $words += count(explode(" ",trim($v)));
}

UPDATE: i corrcted the regexp a bit


can be done using following two functions

function getTextBetweenTags($string, $tagname)
 {
    $pattern = "/<$tagname>(.*?)<\/$tagname>/";
    preg_match($pattern, $string, $matches);
    return $matches[1];
 }


function count_words($str) 
 {
 $no = count(explode(" ",$str));
 return $no;
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜