请问本站的付费文章试读功能咋实现的

现在遇到同样的问题,数据库存的内容存的是富媒体内容,携带 html 标签内容。粗暴的字符串长度截取肯定是不行了。 会遇到标签不一致的问题。 然后就是做个单独的试读内容填写。这样有点 low ,还有更好的方式吗

by JeffreyBool blog :point_right: link
JeffreyBool
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
Summer
最佳答案

对 HTML 进行截断:

closetags(str_limit($article->body, 1000))

闭合标签:

function closetags($html) {
    libxml_use_internal_errors(true);

    $dom = new \DOMDocument;
    $dom->loadHTML('<meta http-equiv="content-type" content="text/html; charset=utf-8">' . $html);

    // Strip wrapping <html> and <body> tags
    $mock = new \DOMDocument;
    $body = $dom->getElementsByTagName('body')->item(0);
    foreach ($body->childNodes as $child) {
        $mock->appendChild($mock->importNode($child, true));
    }

    return trim($mock->saveHTML());
}
4年前 评论
讨论数量: 6
Summer

对 HTML 进行截断:

closetags(str_limit($article->body, 1000))

闭合标签:

function closetags($html) {
    libxml_use_internal_errors(true);

    $dom = new \DOMDocument;
    $dom->loadHTML('<meta http-equiv="content-type" content="text/html; charset=utf-8">' . $html);

    // Strip wrapping <html> and <body> tags
    $mock = new \DOMDocument;
    $body = $dom->getElementsByTagName('body')->item(0);
    foreach ($body->childNodes as $child) {
        $mock->appendChild($mock->importNode($child, true));
    }

    return trim($mock->saveHTML());
}
4年前 评论
JeffreyBool
4年前 评论
4年前 评论
JeffreyBool (楼主) 4年前
Summer

对 HTML 进行截断:

closetags(str_limit($article->body, 1000))

闭合标签:

function closetags($html) {
    libxml_use_internal_errors(true);

    $dom = new \DOMDocument;
    $dom->loadHTML('<meta http-equiv="content-type" content="text/html; charset=utf-8">' . $html);

    // Strip wrapping <html> and <body> tags
    $mock = new \DOMDocument;
    $body = $dom->getElementsByTagName('body')->item(0);
    foreach ($body->childNodes as $child) {
        $mock->appendChild($mock->importNode($child, true));
    }

    return trim($mock->saveHTML());
}
4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!