PHP截取内容指定行数之前或之后的内容
四种方式:
// 保留第3行及之后
sliceLines($content, 3, 'after_inclusive');
// 保留第3行之后(不包含第3行)
sliceLines($content, 3, 'after_exclusive');
// 保留第3行及之前
sliceLines($content, 3, 'before_inclusive');
// 保留第3行之前(不包含第3行)
sliceLines($content, 3, 'before_exclusive');
function sliceLines(string $content, int $target, string $mode = 'after_inclusive', string $eol = null): string{
if ($target < 1) {
return $content;
}
// 修复点1:补全三元运算符的括号
$eol = $eol ?? (strpos($content, "\r\n") !== false ? "\r\n" : "\n");
// 分割为行数组(保留空行)
$lines = preg_split('/\R/', $content);
// 修复点2:添加总行数校验
$total = count($lines);
if ($target > $total) {
return in_array($mode, ['before_inclusive', 'before_exclusive']) ? $content : '';
}
// 根据模式计算切片参数
switch ($mode) {
case 'after_inclusive':
$offset = $target - 1;
$length = null;
break;
case 'after_exclusive':
$offset = $target;
$length = null;
break;
case 'before_inclusive':
$offset = 0;
$length = $target;
break;
case 'before_exclusive':
$offset = 0;
$length = $target - 1;
break;
default:
return $content;
}
// 执行数组切片
$result = array_slice($lines, $offset, $length);
// 还原换行符并返回
return implode($eol, $result);
}
更多推荐内容
- CentOS服务器上用Squid搭建带认证的HTTP代理最简单便捷的方法 14 小时前
- PHP最新获取QQ昵称源码[学习] 17 天前
- 网站从被 K 到恢复收录与排名,我做了这些!! 18 天前
- WordPress当搜索结果为零时,跳转到首页 20 天前
- 突破Nginx中文PDF预览瓶颈:Nginx配置文件与Script脚本解法 20 天前
- 如何查找百度、抖音、微信、微博、小红书、知乎、B站、视频号、快手等7天内最热门话题 21 天前
- 红帽 RHCE 认证精品班30期 26 天前
- QQ群相册下载工具v0.1.4绿色版 27 天前
- 公众号及文章怎么做推荐流量与搜索流量方法揭秘 1 个月前
- 超简约UI外卖券优惠吸粉代码 3 个月前

文章采用: 《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》许可协议授权。
版权声明:本站资源来自互联网收集,仅供用于学习和交流,请勿用于商业用途。如有侵权、不妥之处,请联系客服并出示版权证明以便删除!
自动点击宝25.06.15多个自动脚本极速点击
« 上一篇
06-20
CentOS服务器上用Squid搭建带认证的HTTP代理最简单便捷的方法
下一篇 »
06-20
发表评论