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

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

by JeffreyBool blog :point_right: link
JeffreyBool
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《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());
}
5年前 评论
讨论数量: 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());
}
5年前 评论
JeffreyBool
5年前 评论
5年前 评论
JeffreyBool (楼主) 5年前
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());
}
5年前 评论

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