PHP substr 但保留 HTML 标签?
我想知道是否有一种优雅的方式来修剪一些文本,同时又可以感知 HTML 标签?
例如,我有这个字符串:
$data = '<strong>some title text here that could get very long</strong>';
假设我需要在页面上返回/输出这个字符串,但希望它不超过 X 个字符。在此示例中我们假设为 35。
然后我使用:
$output = substr($data,0,20);
但现在我最终得到:
<strong>some title text here that
如您所见,关闭的强标记被丢弃,从而破坏了 HTML 显示。
有办法解决这个问题吗?另请注意,字符串中可以有多个标签,例如:
<p>some text here <strong>and here</strong></p>
I am wondering if there is an elegant way to trim some text but while being HTML tag aware?
For example, I have this string:
$data = '<strong>some title text here that could get very long</strong>';
And let's say I need to return/output this string on a page but would like it to be no more than X characters. Let's say 35 for this example.
Then I use:
$output = substr($data,0,20);
But now I end up with:
<strong>some title text here that
which as you can see the closing strong tags are discarded thus breaking the HTML display.
Is there a way around this? Also note that it is possible to have multiple tags in the string for example:
<p>some text here <strong>and here</strong></p>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
几个月前,我创建了一个特殊的函数来解决您的问题。
这是一个函数:
这是演示: http://sandbox.onlinephpfunctions.com/code/899d8137c15596a8528c871543eb005984ec0201(单击“执行代码”检查其工作原理)。
A few mounths ago I created a special function which is solution for your problem.
Here is a function:
Here is DEMO: http://sandbox.onlinephpfunctions.com/code/899d8137c15596a8528c871543eb005984ec0201 (click "Execute code" to check how it works).
使用 @newbieuser 他的函数,我遇到了同样的问题,就像 @pablo-pazos 一样,当 $limit 落入 html 标签时(在我的情况下
在 r)用一些代码修复
Using @newbieuser his function, I had the same issue, like @pablo-pazos, that it was (not) breaking when $limit fell into an html tag (in my case
<br />
at the r)Fixed with some code
substr(strip_tags($内容), 0, 100)
substr(strip_tags($content), 0, 100)