下面我使用的substr。从我的数据库中回显前38个字符。这段代码打破了最后的一句话。
<?php echo substr(ucfirst($row['metadesc']),0,38); ?>...
这样的输出。
news for today was null try tomo
如何在单词结束后的38个字符后停止字符串。
输出应该是这样的
news for today was null try tomorrow
答案 0 :(得分:1)
function TrimString($String, $Length)
{
if(strlen($String) > $Length)
{
$Temp[0] = substr($String, 0, $Length);
$Temp[1] = substr($String, $Length);
$SpacePos = strpos($Temp[1], ' ');
if($SpacePos !== FALSE)
{
return $Temp[0].substr($Temp[1], 0, $SpacePos);
}
}
return $String;
}
答案 1 :(得分:0)
function substrword($str, $begin, $length)
{
if (($begin + $length) < strlen($str)) {
return substr($str, $begin, $length).current(explode(' ', substr($str, $length))).'...';
}
return $str;
}
答案 2 :(得分:0)
您可以使用此正则表达式:
preg_match('/^(.{1,38})\b/u', $string, $matches);
你的字符串将是:
$matches[1]