开发者

How to deal with html excerpt?

开发者 https://www.devze.com 2022-12-15 14:10 出处:网络
It introduc开发者_开发技巧ed a lot of non-closed tags like below: <div> <table>...</table>

It introduc开发者_开发技巧ed a lot of non-closed tags like below:

<div>
<table>...</table>

The </div> is truncated by code like this:

(strlen($row['body']) > 200 ? substr($row['body'],0,200) . '...' : $row['body'])

And the layout of the whole page is broken,how to deal with it?


Assuming that $row['body'] contains HTML that you want to truncate to 200 visible characters:

Strip out HTML Tags

This is the quickest fix but may not be what you want:

$body= strip_tags($row['body']);
echo(strlen($body) > 200 ? substr($body,0,200) . '...' : $body);

Parse HTML and truncate text

Using PHP's DOMDocument class you can parse the HTML, check the length of text within HTML tags, count the length of text in the content, and remove any tags after the character limit from the HTML contained in $row['body'] while retaining well-formed HTML.


Here is an example of how to create a post preview or excerpt that contains valid HTML. It parses the HTML using PHP's DOMDocument as leepowers suggested:

http://bizzybytes.com/html-excerpt-php


I assume you have left it out for brevity but I see no tags

it should be

<div>
<table><tr><td>...</td></tr></table>

Also use the following you may have html embedded in your $row['body']

(strlen($row['body']) > 200 ? substr($row['body'],0,200) . '...' : htmlspecialchars($row['body']))

DC

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号