我需要计算span标签中的单词数量......文本通常类似于
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>
任何人都可以指导我如何计算span标签中的单词数量。
由于
答案 0 :(得分:1)
在服务器端,以下计算一个计数器中span标记中的单词,但您可以对所有span元素单独执行此操作。
$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)));
}
更新:我有点损坏了正则表达式
答案 1 :(得分:0)
可以使用以下两个函数来完成
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;
}