用PHP将字符串切成指定的长度
使用该substr()功能可以将字符串切成指定的长度。例如,以下字符串变量,我们最多可以剪切30个字符。
$string='Thisstringistoolongandwillbecutshort.';
该substr()函数具有三个参数。第一个是字符串,第二个是从哪里开始剪切,第三个是要剪切到的字符数。因此,要减少到30个字符,我们将使用以下内容。
$string=substr($string,0,30);
现在将字符串变量设置为以下内容。
Thisstringistoolongandwi
此示例突出了此函数的主要问题,因为它将不理会字符串中的单词。解决方案是创建一个新功能,该功能将在将字符串切成多个字符时避免将单词切开。
function substrwords($text, $maxchar, $end='...') {
if (strlen($text) > $maxchar || $text == '') {
$words = preg_split('/\s/', $text);
$output = '';
$i = 0;
while (1) {
$length = strlen($output)+strlen($words[$i]);
if ($length > $maxchar) {
break;
}
else {
$output .= " " . $words[$i];
++$i;
}
}
$output .= $end;
}
else {
$output = $text;
}
return $output;
}此函数将字符串拆分为单词,然后将它们再次一个接一个地重新连接在一起。好处是,如果有一个单词会使字符串长于所需的字符数,则不包含该单词。可以这样调用该函数。
echosubstrwords($string,30);
这将产生以下输出。
Thisstringistoolongand...
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下