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

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

by JeffreyBool blog :point_right: link
JeffreyBool
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 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年前 评论
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年前

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