可能重复:
缩短 PHP 中的字符串(仅限完整单词)
在我使用的 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
可能重复:
缩短 PHP 中的字符串(仅限完整单词)
在我使用的 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
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;
}
function substrword($str, $begin, $length)
{
if (($begin + $length) < strlen($str)) {
return substr($str, $begin, $length).current(explode(' ', substr($str, $length))).'...';
}
return $str;
}
您可以使用此正则表达式:
preg_match('/^(.{1,38})\b/u', $string, $matches);
您的字符串将是:
$matches[1]