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

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

by JeffreyBool blog :point_right: link
JeffreyBool
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
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年前 评论

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