gpt4 book ai didi

php - 在第四个换行符后切断字符串

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:36:32 25 4
gpt4 key购买 nike

我遇到了问题,我想在第四个换行符之后截断一个长字符串,并让它以“...”继续

<?php
$teststring = "asddsadsadsadsaa\n
asddsadsadsadsaa\n
asddsadsadsadsaa\n
asddsadsadsadsaa\n
asddsadsadsadsaa\n
asddsadsadsadsaa\n";
?>

应该变成:

<?php
$teststring = "asddsadsadsadsaa\n
asddsadsadsadsaa\n
asddsadsadsadsaa\n
asddsadsadsadsaa...";
?>

我知道如何在第一个 \n 之后断开字符串,但我不知道如何在第四个之后断开。

我希望你能帮助我。

最佳答案

你可以把绳子拆开,然后把你需要的所有部分都拿出来

$newStr = ""; // initialise the string
$arr = explode("\n", $teststring);
if(count($arr) > 4) { // you've got more than 4 line breaks
$arr = array_splice($arr, 0, 4); // reduce the lines to four
foreach($arr as $line) { $newStr .= $line; } // store them all in a string
$newStr .= "...";
} else {
$newStr = $teststring; // there was less or equal to four rows so to us it'all ok
}

关于php - 在第四个换行符后切断字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8503028/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com