Php substr整词
如何从$xbio中替换20个字符并仅获取完整单词Php substr整词,php,Php,如何从$xbio中替换20个字符并仅获取完整单词 $xbio = 'word1 ord2 word3 word4 and so on'; echo ''.substr($xbio, 0, 20).'...'; 泰 找到此搜索堆栈溢出-请告诉我您的想法: <? $xbio = preg_replace('/\s+?(\S+)?$/', '', substr($xbio, 0, 50)); ?> 这是我用于此类任务的函数: function truncate($str, $maxLe
$xbio = 'word1 ord2 word3 word4 and so on';
echo ''.substr($xbio, 0, 20).'...';
泰
找到此搜索堆栈溢出-请告诉我您的想法:
<? $xbio = preg_replace('/\s+?(\S+)?$/', '', substr($xbio, 0, 50)); ?>
这是我用于此类任务的函数:
function truncate($str, $maxLength, $append = '...') {
if (strlen($str) > $maxLength) {
$str = substr($str, 0, $maxLength);
$str = preg_replace('/\s+.*?$/', '', $str); // this line is important for you
$str = trim($str);
$str .= $append:
}
return $str;
}
这是我经常使用的功能:
# advanced substr
function gen_string($string,$min) {
$text = trim(strip_tags($string));
if(strlen($text)>$min) {
$blank = strpos($text,' ');
if($blank) {
# limit plus last word
$extra = strpos(substr($text,$min),' ');
$max = $min+$extra;
$r = substr($text,0,$max);
if(strlen($text)>=$max) $r=trim($r,'.').'...';
} else {
# if there are no spaces
$r = substr($text,0,$min).'...';
}
} else {
# if original length is lower than limit
$r = $text;
}
return $r;
}
看一看,你必须先定义一个术语“单词”。PHP不知道你的意思。我认为你的
preg\u replace
遗漏了一些参数。:)对不起,我打了20分。。30分钟的测试。这最多匹配20个字符,但使其必须在空格或行的结尾处\b而不是“(|$)”匹配\b匹配单词边界,并覆盖当前方法遗漏的其他换行符,如换行符、制表符等。有关详细信息,请参阅。
# advanced substr
function gen_string($string,$min) {
$text = trim(strip_tags($string));
if(strlen($text)>$min) {
$blank = strpos($text,' ');
if($blank) {
# limit plus last word
$extra = strpos(substr($text,$min),' ');
$max = $min+$extra;
$r = substr($text,0,$max);
if(strlen($text)>=$max) $r=trim($r,'.').'...';
} else {
# if there are no spaces
$r = substr($text,0,$min).'...';
}
} else {
# if original length is lower than limit
$r = $text;
}
return $r;
}