有没有一种方法可以在PHP中修剪文本字符串,使其具有一定数量的字符?例如,如果我有字符串:
$string = "this is a string";
我怎么修剪它说:
$newstring = "this is";
到目前为止,这是我目前使用的chunk_split(),但是没有用。谁能改善我的方法?
function trimtext($text)
{
$newtext = chunk_split($text,15);
return $newtext;
}
Run Code Online (Sandbox Code Playgroud)
我也看了这个问题,但我不太了解。
if (strlen($yourString) > 15) // if you want...
{
$maxLength = 14;
$yourString = substr($yourString, 0, $maxLength);
}
Run Code Online (Sandbox Code Playgroud)
会做的工作。
在这里看看。
substr 将单词切成两半。此外,如果 word 包含 UTF8 字符,则会出现错误行为。所以最好使用mb_substr:
$string = mb_substr('word word word word', 0, 10, 'utf8').'...';
您没有说出这样做的原因,而是考虑您想要实现的目标。这是一个用于逐个单词地缩短字符串的功能,该字符串的末尾带有或不带有省略号:
function limitStrlen($input, $length, $ellipses = true, $strip_html = true) {
//strip tags, if desired
if ($strip_html) {
$input = strip_tags($input);
}
//no need to trim, already shorter than trim length
if (strlen($input) <= $length) {
return $input;
}
//find last space within length
$last_space = strrpos(substr($input, 0, $length), ' ');
if($last_space !== false) {
$trimmed_text = substr($input, 0, $last_space);
} else {
$trimmed_text = substr($input, 0, $length);
}
//add ellipses (...)
if ($ellipses) {
$trimmed_text .= '...';
}
return $trimmed_text;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13023 次 |
| 最近记录: |