截断包含HTML的文本,忽略标记

时间:2009-07-28 11:30:29

标签: php html string markup

我想截断一些文本(从数据库或文本文件加载),但它包含HTML,因此包含标记并返回较少的文本。这可能导致标签未被关闭或部分关闭(因此整洁可能无法正常工作且内容仍然较少)。如何根据文本进行截断(当你到达某个表时可能会停止,因为这可能会导致更复杂的问题)。

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个字符)。

strip_tags是一个后备,但我会丢失格式和链接,它仍然会遇到HTML实体的问题。

13 个答案:

答案 0 :(得分:46)

假设您使用的是有效的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作为第三个参数。不支持其他多字节编码,但在调用函数之前使用mb_convert_encoding转换为UTF-8,然后在每个print语句中再次转换回来可能会支持。

(你应该总是使用UTF-8。)

编辑:已更新以处理字符实体和UTF-8。修复了如果该字符是字符实体,函数将打印一个字符太多的错误。

答案 1 :(得分: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; 
        }

答案 2 :(得分:4)

100%准确,但相当困难的方法:

  1. Iterate charactes using DOM
  2. 使用DOM方法删除剩余元素
  3. 序列化DOM
  4. 简单的蛮力方法:

    1. 使用带有PREG_DELIM_CAPTURE的preg_split('/(<tag>)/')将字符串拆分为标记(不是元素)和文本片段。
    2. 测量您想要的文字长度(它将是分割中的每一个元素,您可以使用html_entity_decode()来帮助准确测量)
    3. 剪切字符串(在末尾修剪&[^\s;]+$以摆脱可能被切碎的实体)
    4. 使用HTML Tidy修复

答案 3 :(得分:4)

我在http://alanwhipple.com/2011/05/25/php-truncate-string-preserving-html-tags-words使用了一个很好的函数,显然取自CakePHP

答案 4 :(得分:2)

以下是一个简单的状态机解析器,它可以成功处理测试用例。我在嵌套标签上失败,因为它不跟踪标签本身。我还对HTML标记中的实体(例如href - <a> - 标记的属性)进行了扼流。所以它不能被认为是这个问题的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;
}

答案 5 :(得分:2)

在这种情况下可以使用一个令人讨厌的正则表达式hack的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>

答案 6 :(得分:2)

我对SørenLø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;   

    }

答案 7 :(得分:2)

Bounce为SørenLøvborg的解决方案增加了多字节字符支持 - 我添加了:

  • 支持未配对的HTML代码(例如<hr><br> <col>等。请勿关闭 - 在HTML中,这些内容不需要'/'(在虽然是针对XHTML)),
  • 可自定义的截断指示符(默认为&hellips;,即......),
  • 在不使用输出缓冲区的情况下以字符串形式返回,
  • 100%覆盖的单元测试。

所有这些都在Pastie

答案 8 :(得分:2)

SørenLøvborg的另一个亮点是更改了printTruncated函数,使UTF-8(需要mbstring)兼容并使其返回字符串而不是打印字符串。我认为它更有用。 而且我的代码不像Bounce变量那样使用缓冲,只是一个变量。

UPD:要使标签属性中的utf-8字符正常工作,您需要mb_preg_match函数,如下所示。

非常感谢SørenLø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;
}

答案 9 :(得分:2)

您也可以使用tidy

function truncate_html($html, $max_length) {   
  return tidy_repair_string(substr($html, 0, $max_length),
     array('wrap' => 0, 'show-body-only' => TRUE), 'utf8'); 
}

答案 10 :(得分:2)

CakePHP框架在TextHelper中有一个支持HTML的truncate()函数,对我有用。见Core-Helpers/Text。麻省理工学院许可证。

答案 11 :(得分:0)

如果不使用验证器和解析器,这很难做到,原因是假设你有

<div id='x'>
    <div id='y'>
        <h1>Heading</h1>
        500 
        lines 
        of 
        html
        ...
        etc
        ...
    </div>
</div>

您打算如何截断并最终获得有效的HTML?

经过简短的搜索,我找到了this link可能有所帮助。

答案 12 :(得分:0)

使用以下功能truncateHTML()https://github.com/jlgrall/truncateHTML

示例:截断9个字符后包括省略号:

truncateHTML(9, "<p><b>A</b> red ball.</p>", ['wholeWord' => false]);
// =>           "<p><b>A</b> red ba…</p>"

功能:UTF-8,可配置省略号,包含/排除省略号长度,自动关闭标记,折叠空格,不可见元素(<head><script>,{ {1}},<noscript><style>),HTML <!-- comments -->,截断最后一个字(带有截断非常长字的选项),PHP 5.6和7.0 +,240 +单位测试,返回一个字符串(不使用输出缓冲区),以及评论良好的代码。

我写了这个函数,因为我真的很喜欢Søren Løvborg上面的函数(特别是他管理编码的方式),但我需要更多的功能和灵活性。