php 字符串截掉前两位,如何在PHP的前20个单词中截断字符串?

到最近的空间

截断到目标字符最近的前一个空格。演示

$str 要截断的字符串

$chars 要剥离的字符数量,可以通过以下方式覆盖 $to_space

$to_space boolean是否从接近$chars极限的空间截断

功能

function truncateString($str, $chars, $to_space, $replacement="...") {

if($chars > strlen($str)) return $str;

$str = substr($str, 0, $chars);

$space_pos = strrpos($str, " ");

if($to_space && $space_pos >= 0)

$str = substr($str, 0, strrpos($str, " "));

return($str . $replacement);

}

样品

$str = "this is a string that is just some text for you to test with";

print(truncateString($str, 20, false) . "\n");

print(truncateString($str, 22, false) . "\n");

print(truncateString($str, 24, true) . "\n");

print(truncateString($str, 26, true, " :)") . "\n");

print(truncateString($str, 28, true, "--") . "\n");

?>

产量

this is a string tha...

this is a string that ...

this is a string that...

this is a string that is :)

this is a string that is--

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值