php - 使用 substr 获取前 x 个字符时如何跳过 HTML 标记
问题描述
在一些博客文件中,我在 500 个字符后使用“阅读更多”按钮。要从字符串(即 blogmessage)中获取前 500 个字符,我使用substr
如下:
$blog_message_reduced = substr($blog_message, 0, 500);
字符串$blog_message
如下所示:
lorem ipsum is simply dummy text of the printing and typesetting industry <img src="data/uploads/image.jpg" class="img-responsive" style="width: 100%" /> and some more text behind the image....
有时,当我写博客文章时,500 个字符的限制正好在img 标签内。
$blog_message_reduced
然后 HTML 输出类似于:
lorem ipsum is simply dummy text of the <img src="data/uplo
在上面的示例中,单词uploads的o已达到500 。
因此,我正在寻找一种方法来在使用 500 进行裁剪时忽略img
标签。substr
(当达到 500 时,切勿剪切img
标签;在这种情况下,请在img
标签后立即剪切)。
我怎样才能做到这一点?
解决方案
在裁剪之前使用 PHP 的strip_tags()。
<?php
$str = 'lorem ipsum is simply dummy text of the printing and typesetting industry <img src="data/uploads/image.jpg" class="img-responsive" style="width: 100%" /> and some more text behind the image.... ';
$pre = strip_tags($str);
$crop = substr($pre, 0, 100);
echo $crop;
// Output:
// lorem ipsum is simply dummy text of the printing and typesetting industry and some more text behind
或与一些更高级的用法相同
<?php
$str = 'lorem ipsum is simply dummy text of the printing and typesetting industry <img src="data/uploads/image.jpg" class="img-responsive" style="width: 100%" /> and some more text behind the image.... ';
echo crop($str, 100, '... (read more)', true, true);
function crop($content, $maxCharacters, $append = '...', $respectWordBoundaries = false, $stripTags = false)
{
if ($stripTags) {
$content = strip_tags($content);
}
if ($maxCharacters) {
if (mb_strlen($content, 'utf-8') > abs($maxCharacters)) {
$truncatePosition = false;
if ($maxCharacters < 0) {
$content = mb_substr($content, $maxCharacters, null, 'utf-8');
if ($respectWordBoundaries) {
$truncatePosition = strpos($content, ' ');
}
$content = $truncatePosition ? $append . substr($content, $truncatePosition) : $append . $content;
} else {
$content = mb_substr($content, 0, $maxCharacters, 'utf-8');
if ($respectWordBoundaries) {
$truncatePosition = strrpos($content, ' ');
}
$content = $truncatePosition ? substr($content, 0, $truncatePosition) . $append : $content . $append;
}
}
}
return $content;
}
推荐阅读
- azure - 流分析不立即处理,恒定 5 秒水印
- r - 在 R 中使用 dplyr 函数过滤数据
- c++ - 访问 std 向量中的 unique_ptrs - 必须提供复制构造函数?
- python - 需要帮助了解 RESTful API 中的 SQL 注入漏洞
- terraform - 使用 Terraform 关闭/打开 Elastic Beanstalk 负载均衡器?
- json - 用于创建 EC2 的 AWS CloudFormation 模板 (JSON) - 意外错误
- python - Pandas DF 列数据拆分
- node.js - Node.js 错误:生成进程 ffmpeg ChildProcessError
- python - struct 打包和解包不正确
- javascript - 如何获取数组中不重复的所有唯一元素