42

一部のテキスト (データベースまたはテキスト ファイルからロードされたもの) を切り捨てたいのですが、HTML が含まれているため、タグが含まれ、返されるテキストが少なくなります。これにより、タグが閉じられなかったり、部分的に閉じられたりする可能性があります (そのため、Tidy が適切に機能せず、コンテンツが少なくなる可能性があります)。テキストに基づいて切り捨てるにはどうすればよいですか (そして、より複雑な問題を引き起こす可能性があるため、テーブルに到達すると停止する可能性があります)。

substr("Hello, my <strong>name</strong> is <em>Sam</em>. I&acute;m a web developer.",0,26)."..."

次のようになります。

Hello, my <strong>name</st...

私が欲しいのは:

Hello, my <strong>name</strong> is <em>Sam</em>. I&acute;m...

これどうやってするの?

私の質問はPHPでそれを行う方法についてですが、C#でそれを行う方法を知っておくとよいでしょう...メソッドを移植できると思うので、どちらでも問題ありません(組み込みでない限り)方法)。

また、HTML エンティティが含まれていることにも注意してください&acute;。これは、(この例のように 7 文字ではなく) 1 文字と見なす必要があります。

strip_tagsはフォールバックですが、書式設定とリンクが失われ、HTML エンティティにまだ問題があります。

4

13 に答える 13

50

有効な XHTML を使用していると仮定すると、HTML を解析して、タグが適切に処理されていることを確認するのは簡単です。これまでにどのタグが開かれたかを追跡し、「途中で」もう一度閉じてください。

<?php
header('Content-type: text/plain; charset=utf-8');

function printTruncated($maxLength, $html, $isUtf8=true)
{
    $printedLength = 0;
    $position = 0;
    $tags = array();

    // For UTF-8, we need to count multibyte sequences as one character.
    $re = $isUtf8
        ? '{</?([a-z]+)[^>]*>|&#?[a-zA-Z0-9]+;|[\x80-\xFF][\x80-\xBF]*}'
        : '{</?([a-z]+)[^>]*>|&#?[a-zA-Z0-9]+;}';

    while ($printedLength < $maxLength && preg_match($re, $html, $match, PREG_OFFSET_CAPTURE, $position))
    {
        list($tag, $tagPosition) = $match[0];

        // Print text leading up to the tag.
        $str = substr($html, $position, $tagPosition - $position);
        if ($printedLength + strlen($str) > $maxLength)
        {
            print(substr($str, 0, $maxLength - $printedLength));
            $printedLength = $maxLength;
            break;
        }

        print($str);
        $printedLength += strlen($str);
        if ($printedLength >= $maxLength) break;

        if ($tag[0] == '&' || ord($tag) >= 0x80)
        {
            // Pass the entity or UTF-8 multibyte sequence through unchanged.
            print($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.

                print($tag);
            }
            else if ($tag[strlen($tag) - 2] == '/')
            {
                // Self-closing tag.
                print($tag);
            }
            else
            {
                // Opening tag.
                print($tag);
                $tags[] = $tagName;
            }
        }

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

    // Print any remaining text.
    if ($printedLength < $maxLength && $position < strlen($html))
        print(substr($html, $position, $maxLength - $printedLength));

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


printTruncated(10, '<b>&lt;Hello&gt;</b> <img src="world.png" alt="" /> world!'); print("\n");

printTruncated(10, '<table><tr><td>Heck, </td><td>throw</td></tr><tr><td>in a</td><td>table</td></tr></table>'); print("\n");

printTruncated(10, "<em><b>Hello</b>&#20;w\xC3\xB8rld!</em>"); print("\n");

エンコードに関する注意: 上記のコードは、XHTML がUTF-8でエンコードされていることを前提としています。ASCII 互換のシングルバイト エンコーディング ( Latin-1など) もサポートfalseされています。3 番目の引数として渡すだけです。他のマルチバイトエンコーディングはサポートされていませんが、関数を呼び出す前に を使用して UTF-8 に変換し、すべてのステートメントmb_convert_encodingで再度変換することで、サポートをハックすることができます。print

(ただし、常にUTF-8 を使用する必要があります。)

編集:文字エンティティと UTF-8 を処理するように更新されました。その文字が文字エンティティの場合、関数が 1 文字を多く出力するバグを修正しました。

于 2009-07-28T11:50:56.733 に答える
5

あなたが提案したようにHTMLを切り捨てる関数を書きましたが、それを印刷する代わりに、すべてを文字列変数に保持します。HTML エンティティも処理します。

 /**
     *  function to truncate and then clean up end of the HTML,
     *  truncates by counting characters outside of HTML tags
     *  
     *  @author alex lockwood, alex dot lockwood at websightdesign
     *  
     *  @param string $str the string to truncate
     *  @param int $len the number of characters
     *  @param string $end the end string for truncation
     *  @return string $truncated_html
     *  
     *  **/
        public static function truncateHTML($str, $len, $end = '&hellip;'){
            //find all tags
            $tagPattern = '/(<\/?)([\w]*)(\s*[^>]*)>?|&[\w#]+;/i';  //match html tags and entities
            preg_match_all($tagPattern, $str, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER );
            //WSDDebug::dump($matches); exit; 
            $i =0;
            //loop through each found tag that is within the $len, add those characters to the len,
            //also track open and closed tags
            // $matches[$i][0] = the whole tag string  --the only applicable field for html enitities  
            // IF its not matching an &htmlentity; the following apply
            // $matches[$i][1] = the start of the tag either '<' or '</'  
            // $matches[$i][2] = the tag name
            // $matches[$i][3] = the end of the tag
            //$matces[$i][$j][0] = the string
            //$matces[$i][$j][1] = the str offest

            while($matches[$i][0][1] < $len && !empty($matches[$i])){

                $len = $len + strlen($matches[$i][0][0]);
                if(substr($matches[$i][0][0],0,1) == '&' )
                    $len = $len-1;


                //if $matches[$i][2] is undefined then its an html entity, want to ignore those for tag counting
                //ignore empty/singleton tags for tag counting
                if(!empty($matches[$i][2][0]) && !in_array($matches[$i][2][0],array('br','img','hr', 'input', 'param', 'link'))){
                    //double check 
                    if(substr($matches[$i][3][0],-1) !='/' && substr($matches[$i][1][0],-1) !='/')
                        $openTags[] = $matches[$i][2][0];
                    elseif(end($openTags) == $matches[$i][2][0]){
                        array_pop($openTags);
                    }else{
                        $warnings[] = "html has some tags mismatched in it:  $str";
                    }
                }


                $i++;

            }

            $closeTags = '';

            if (!empty($openTags)){
                $openTags = array_reverse($openTags);
                foreach ($openTags as $t){
                    $closeTagString .="</".$t . ">"; 
                }
            }

            if(strlen($str)>$len){
                // Finds the last space from the string new length
                $lastWord = strpos($str, ' ', $len);
                if ($lastWord) {
                    //truncate with new len last word
                    $str = substr($str, 0, $lastWord);
                    //finds last character
                    $last_character = (substr($str, -1, 1));
                    //add the end text
                    $truncated_html = ($last_character == '.' ? $str : ($last_character == ',' ? substr($str, 0, -1) : $str) . $end);
                }
                //restore any open tags
                $truncated_html .= $closeTagString;


            }else
            $truncated_html = $str;


            return $truncated_html; 
        }
于 2012-03-06T18:30:31.863 に答える
4

http://alanwhipple.com/2011/05/25/php-truncate-string-preserving-html-tags-wordsにある素敵な関数を使用しました。明らかに CakePHP から取得したものです。

于 2012-01-12T19:43:47.650 に答える
4

100% 正確ですが、かなり難しいアプローチ:

  1. DOM を使用して文字を繰り返す
  2. DOM メソッドを使用して残りの要素を削除する
  3. DOM をシリアライズする

簡単な力ずくのアプローチ:

  1. preg_split('/(<tag>)/')PREG_DELIM_CAPTUREを使用して、文字列をタグ (要素ではない) とテキスト フラグメントに分割します。
  2. 必要なテキストの長さを測定します (分割から 2 つおきの要素になります。html_entity_decode()正確に測定するために使用できます) 。
  3. 文字列をカットします (&[^\s;]+$切り刻まれた可能性のあるエンティティを取り除くために最後をトリムします)。
  4. HTML Tidy で修正する
于 2009-07-28T12:04:36.987 に答える
3

以下は、テスト ケースを正常に処理する単純なステート マシン パーサーです。タグ自体を追跡しないため、ネストされたタグでは失敗します。また、HTML タグ内のエンティティ ( href-tag の<a>-attribute など) をチョークします。したがって、この問題に対する 100% の解決策とは見なされませんが、理解しやすいため、より高度な機能の基礎となる可能性があります。

function substr_html($string, $length)
{
    $count = 0;
    /*
     * $state = 0 - normal text
     * $state = 1 - in HTML tag
     * $state = 2 - in HTML entity
     */
    $state = 0;    
    for ($i = 0; $i < strlen($string); $i++) {
        $char = $string[$i];
        if ($char == '<') {
            $state = 1;
        } else if ($char == '&') {
            $state = 2;
            $count++;
        } else if ($char == ';') {
            $state = 0;
        } else if ($char == '>') {
            $state = 0;
        } else if ($state === 0) {
            $count++;
        }

        if ($count === $length) {
            return substr($string, 0, $i + 1);
        }
    }
    return $string;
}
于 2009-07-28T12:01:35.793 に答える
3

tidyも使用できます。

function truncate_html($html, $max_length) {   
  return tidy_repair_string(substr($html, 0, $max_length),
     array('wrap' => 0, 'show-body-only' => TRUE), 'utf8'); 
}
于 2012-09-10T08:23:59.963 に答える
2

Bounce は、Søren Løvborg のソリューションにマルチバイト文字のサポートを追加しました - 私は以下を追加しました:

  • ペアになっていない HTML タグのサポート (例:<hr>など<br> <col>は閉じられません - HTML では、これらの末尾に「/」は必要ありません (ただし、XHTML の場合))、
  • カスタマイズ可能な切り捨てインジケータ (デフォルトは&hellips;ie … ),
  • 出力バッファを使用せずに文字列として返す、および
  • 100% カバレッジの単体テスト。

これらすべてパスティで。

于 2011-12-28T11:19:42.323 に答える
2

この場合、厄介な正規表現ハックで DomDocument を使用できます。壊れたタグがある場合、最悪の場合は警告が発生します。

$dom = new DOMDocument();
$dom->loadHTML(substr("Hello, my <strong>name</strong> is <em>Sam</em>. I&acute;m a web developer.",0,26));
$html = preg_replace("/\<\/?(body|html|p)>/", "", $dom->saveHTML());
echo $html;

出力を与える必要があります: Hello, my <strong>**name**</strong>.

于 2009-07-28T12:41:00.787 に答える
2

Søren Løvborg の printTruncated 関数に別のライトが変更され、UTF-8 (mbstring が必要) と互換性があり、印刷ではなく文字列が返されるようになりました。より便利だと思います。そして、私のコードは Bounce バリアントのようなバッファリングを使用せず、変数を 1 つだけ使用します。

UPD: タグ属性の utf-8 文字で適切に動作させるには、以下に示す mb_preg_match 関数が必要です。

その機能について Søren Løvborg に感謝します。非常に優れています。

/* Truncate HTML, close opened tags
*
* @param int, maxlength of the string
* @param string, html       
* @return $html
*/

function htmlTruncate($maxLength, $html)
{
    mb_internal_encoding("UTF-8");
    $printedLength = 0;
    $position = 0;
    $tags = array();
    $out = "";

    while ($printedLength < $maxLength && mb_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_substr($html, $position, $tagPosition - $position);
        if ($printedLength + mb_strlen($str) > $maxLength)
        {
            $out .= mb_substr($str, 0, $maxLength - $printedLength);
            $printedLength = $maxLength;
            break;
        }

        $out .= $str;
        $printedLength += mb_strlen($str);

        if ($tag[0] == '&')
        {
            // Handle the entity.
            $out .= $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.

                $out .= $tag;
            }
            else if ($tag[mb_strlen($tag) - 2] == '/')
            {
                // Self-closing tag.
                $out .= $tag;
            }
            else
            {
                // Opening tag.
                $out .= $tag;
                $tags[] = $tagName;
            }
        }

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

    // Print any remaining text.
    if ($printedLength < $maxLength && $position < mb_strlen($html))
        $out .= mb_substr($html, $position, $maxLength - $printedLength);

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

    return $out;
}

function mb_preg_match(
    $ps_pattern,
    $ps_subject,
    &$pa_matches,
    $pn_flags = 0,
    $pn_offset = 0,
    $ps_encoding = NULL
) {
    // WARNING! - All this function does is to correct offsets, nothing else:
    //(code is independent of PREG_PATTER_ORDER / PREG_SET_ORDER)

    if (is_null($ps_encoding)) $ps_encoding = mb_internal_encoding();

    $pn_offset = strlen(mb_substr($ps_subject, 0, $pn_offset, $ps_encoding));
    $ret = preg_match($ps_pattern, $ps_subject, $pa_matches, $pn_flags, $pn_offset);

    if ($ret && ($pn_flags & PREG_OFFSET_CAPTURE))
        foreach($pa_matches as &$ha_match) {
                $ha_match[1] = mb_strlen(substr($ps_subject, 0, $ha_match[1]), $ps_encoding);
        }

    return $ret;
}
于 2012-01-15T09:34:42.723 に答える
2

CakePHPフレームワークには、テキスト ヘルパーに HTML 対応の truncate() 関数があり、私にとってはうまくいきます。テキストを参照してください。MIT ライセンス。ソースへのリンク(@Quentin 提供)。

于 2013-03-20T18:18:16.550 に答える
2

Søren LøvborgprintTruncated関数に軽い変更を加えて、UTF-8 互換にしました。

   /* Truncate HTML, close opened tags
    *
    * @param int, maxlength of the string
    * @param string, html       
    * @return $html
    */  
    function html_truncate($maxLength, $html){

        mb_internal_encoding("UTF-8");

        $printedLength = 0;
        $position = 0;
        $tags = array();

        ob_start();

        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){
                print(mb_strcut($str, 0, $maxLength - $printedLength));
                $printedLength = $maxLength;
                break;
            }

            print($str);
            $printedLength += mb_strlen($str);

            if ($tag[0] == '&'){
                // Handle the entity.
                print($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.

                    print($tag);
                }
                else if ($tag[mb_strlen($tag) - 2] == '/'){
                    // Self-closing tag.
                    print($tag);
                }
                else{
                    // Opening tag.
                    print($tag);
                    $tags[] = $tagName;
                }
            }

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

        // Print any remaining text.
        if ($printedLength < $maxLength && $position < mb_strlen($html))
            print(mb_strcut($html, $position, $maxLength - $printedLength));

        // Close any open tags.
        while (!empty($tags))
             printf('</%s>', array_pop($tags));


        $bufferOuput = ob_get_contents();

        ob_end_clean();         

        $html = $bufferOuput;   

        return $html;   

    }
于 2011-11-22T14:53:10.883 に答える