считать слова в теге span - PullRequest
       1

считать слова в теге span

0 голосов
/ 04 февраля 2011

Мне нужно посчитать количество слов в теге 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.

Спасибо

Ответы [ 2 ]

1 голос
/ 04 февраля 2011

На стороне сервера следующее подсчитывает слова в тегах 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)));
}

UPDATE: я исправленрегулярное выражение немного

0 голосов
/ 04 февраля 2011

можно сделать с помощью следующих двух функций

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;
 }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...