试图构建一个php摘录函数

时间:2014-09-02 19:37:31

标签: php regex

我从数据库中的字段中提取了大量内容。

此内容可以是标准

中的任何内容
Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, 
when an unknown printer took a galley of type and scrambled it to make a type 
specimen book.

涉及一个涉及html标签的更复杂的字符串。

Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
<a href="">Lorem Ipsum</a> has been the industry's <strong>standard</strong> 
dummy text ever since the 1500s, when an unknown printer took a <b>galley</b> 
of type and scrambled it to make a type specimen book.

现在我首次尝试的简单方法就是简单地使用

substr($row['Description'],0,250);
然而,我很快意识到,当文本在标签中间被切断时,会导致问题,有效地加粗和/或链接其后的所有内容。

我用谷歌搜索了我的屁股,但所有出现的都是一个word-press插件/插件。这不是很有帮助。

所以我需要构建一个考虑到

的功能
  1. 字符限制
  2. 检查限制是否在标记内结束,并扩展限制以关闭标记。
  3. 例如,如果限制为10:

    <?php
    $string="Hello this is a dummy text";
    echo substr($string,0,10);
    //output = "Hello this"
    
    $string="Hello <b>this is a dummy</b> text";
    //Better excerpt function
    //output = "Hello this is a dummy"
    

    非常感谢任何帮助。

    到目前为止,我已经编造了这个悲伤的小功能。我只知道有一种更清洁的方法。此功能也不理想,因为它只考虑它找到的第一个标签。 但至少它可能会更好地解决问题。

    function eventExcerpt($text)
    {
        #echo $text;
    
        $excerpt = substr($text, 0, 250);
    
        $opening_tags = array('<a', '<p', '<ul', '<li', '<b', '<strong', '<span', '<div');
        $closing_tags = array('</a>','</p>','</ul>','</li>','</b>','</strong>','</span>','</div>');
    
        $has_html = 0;
    
        foreach($opening_tags as $key => $val)
            {
                if(strpos($excerpt, $val))
                    {
                        // Found an opening_tag within the excerpt
                        $has_html = $key;
                        break;
                    }
            }
    
    
        if($has_html != "")
            {
                // echo text up until the closing_tag it found within excerpt but using text
                $closed_tag_pos = strpos($text, $closing_tags[$has_html]);
                echo substr($text, 0, $closed_tag_pos);
            }
        else
            {
                // echo excerpt since no opening_tags were found
                echo $excerpt;
            }
    }
    

    我还应该提一下,我正在运行PHP 5.2.5

1 个答案:

答案 0 :(得分:2)

您可以使用Tidy extension轻松完成工作。例如:

$tidyText = new Tidy();
$options = array('indent' => true);

$text = substr($yourText, 0, 250) . '...';
$tidyText->parseString($text, $options);
$tidyText->cleanRepair();
echo $tidyText;

这将在剥离完成后自动修复未关闭/不匹配的标签,以便您获得正确的摘录。

注意:确保从php.ini开启Tidy扩展

没有Tidy扩展的替代方案:

您也可以尝试使用DOMDocument

$dom = new DOMDocument;
$dom->loadHTML($yourText);
$clean = $dom->saveXML();
echo $clean;