duandange7480 2014-09-27 16:49
浏览 87
已采纳

如果达到一定数量的换行符,则剪切字符串

How can I cut a string in PHP if there's a certain amount of newlines? For example, say the string was 10 lines of text, all on a new line, how could I cut that string so that only the first 5 lines showed? I already cut the string to 650 characters, however, I'd also like to be able to cut it, should it reach too many newlines.

Current code that cuts the string if it's above 650 characters:

$string = $f2;
$maxLength = 650;

if (strlen($string) > $maxLength) {
    $stringCut = substr($string, 0, $maxLength);
    $string = substr($stringCut, 0, strrpos($stringCut, ' ')); 
}
$stringchar=htmlspecialchars($string);
echo nl2br($stringchar);
  • 写回答

2条回答 默认 最新

  • doutan5798 2014-09-27 16:53
    关注

    You can use this regex to capture first 1-5 lines of multiline input:

    ([^
    ]*\R){1,5}
    

    RegEx Demo

    Code:

    if (preg_match('/([^
    ]*\R){1,5}/', $input, $m))
       print_r($m);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?