2011-12-14 10 views
4

私はHTMLタグを含む文字列を持っています。私は、私はこの文字列を切り捨て聞かせコードの部分を探しています:100文字の長さを持っているHTMLタグで文字列を切り捨てます

  • にイメージタグ(<img />)が含まれていません。
  • 他のHTMLタグ(イメージタグを除く)、
  • には、100文字の長さに空白とHTMLタグ文字を含めないでください。たとえば、

、文字列は次のとおりです。

<img>Something</img><b>Just an Example</b> Plain Text <br><a href="#">stackoverflow</a> 

だから、結果は次のようになります。

は一例プレーンテキストのstackoverflow(そのリンク)。

結果として約35語(空白を除く)があります。

私はthis questionの解決策を試しましたが、必要な結果が得られませんでした。どんな助けもありがとう。

+0

これを行うのに役立ついくつかのPHPテンプレートモジュール/フレームワークを試しましたか? –

+0

どのような結果が必要なものと異なっていましたか? – Herbert

+0

@Herbert - 文字列の長さ全体でhtmlタグと空白を数える文字列を取得しています。だから私は100単語の文字列を切り捨てるときに私は80単語を取得し、休憩カウントは空白とHTMLタグのためだった。質問に答えることで私にいくつかのヒントを与えてください。ありがとう。 –

答えて

5

機能はどうですか。ここに私の - AbstractHTMLContentsです。

  • 入力HTMLコンテンツ、
  • 制限:これは、2つのパラメータがあります。

は、ここでは、コードです:

function AbstractHTMLContents($html, $maxLength=100){ 
    mb_internal_encoding("UTF-8"); 
    $printedLength = 0; 
    $position = 0; 
    $tags = array(); 
    $newContent = ''; 

    $html = $content = preg_replace("/<img[^>]+\>/i", "", $html); 

    while ($printedLength < $maxLength && preg_match('{</?([a-z]+)[^>]*>|&#?[a-zA-Z0-9]+;}', $html, $match, PREG_OFFSET_CAPTURE, $position)) 
    { 
     list($tag, $tagPosition) = $match[0]; 
     // Print text leading up to the tag. 
     $str = mb_strcut($html, $position, $tagPosition - $position); 
     if ($printedLength + mb_strlen($str) > $maxLength){ 
      $newstr = mb_strcut($str, 0, $maxLength - $printedLength); 
      $newstr = preg_replace('~\s+\S+$~', '', $newstr); 
      $newContent .= $newstr; 
      $printedLength = $maxLength; 
      break; 
     } 
     $newContent .= $str; 
     $printedLength += mb_strlen($str); 
     if ($tag[0] == '&') { 
      // Handle the entity. 
      $newContent .= $tag; 
      $printedLength++; 
     } else { 
      // Handle the tag. 
      $tagName = $match[1][0]; 
      if ($tag[1] == '/') { 
       // This is a closing tag. 
       $openingTag = array_pop($tags); 
       assert($openingTag == $tagName); // check that tags are properly nested. 
       $newContent .= $tag; 
      } else if ($tag[mb_strlen($tag) - 2] == '/'){ 
      // Self-closing tag. 
      $newContent .= $tag; 
     } else { 
      // Opening tag. 
      $newContent .= $tag; 
      $tags[] = $tagName; 
     } 
     } 

     // Continue after the tag. 
     $position = $tagPosition + mb_strlen($tag); 
    } 

    // Print any remaining text. 
    if ($printedLength < $maxLength && $position < mb_strlen($html)) 
     { 
     $newstr = mb_strcut($html, $position, $maxLength - $printedLength); 
     $newstr = preg_replace('~\s+\S+$~', '', $newstr); 
     $newContent .= $newstr; 
     } 

    // Close any open tags. 
    while (!empty($tags)) 
     { 
     $newContent .= sprintf('</%s>', array_pop($tags)); 
     } 

    return $newContent; 
} 

それはそう、それはあなたが期待する結果が得られます。

+0

上記のコードに相当するjavascriptはありませんか? – furiabhavesh

+0

この問題の最良の解決策の1つは、私が会ったことです。よくやった! – trejder

関連する問題