我有一个测试区域,它是来自数据库的动态文本可能有数千个单词。 我希望它打破并使每个段落在100(任何长度)单词附近完全停止。 我可以在100个单词之后休息,但不能完全停止。 为了在100(任何长度)单词后休息,我使用了以下功能。
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 TrimString($String, $Length){
if(strlen($String)<=$Length){
$stringValue=$String;
} else {
$stringValue=substr($String,0,$Length) . '.';
}
return $stringValue;
}
$m=50;
$a="I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. ";
$data=TrimString($a,$m);
echo $data;
它为我提供了答案
I am a boy. I am a boy. I am a boy. I am a boy. I .
但我需要答案
I am a boy. I am a boy. I am a boy. I am a boy.
那么你可以帮我找到提供给该功能的长度附近的句号并打破段落。
答案 0 :(得分:1)
在此添加句号(.)
,如
return $Temp[0].substr($Temp[1], 0, $SpacePos).".";
更新2:
<?php
function TrimString($String, $Length){
if(strlen($String)<=$Length){
$stringValue=$String;
} else {
$new_l = strpos ($String , ".", $Length);
$Length = $new_l+1;
$stringValue=substr($String,0,$Length);
}
return $stringValue;
}
$m=50;
$a="I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. I am a boy. ";
$data=TrimString($a,$m);
echo $data;
?>
输出:
I am a boy. I am a boy. I am a boy. I am a boy. I am a boy.
答案 1 :(得分:0)
function TrimString($String, $Length){
if(strlen($String)<=$Length){
$stringValue=$String;
} else {
$stringValue=substr($String,0,$Length) . '.';
}
return $stringValue;
}
you are looking like this:
function TrimString($String, $Length){
if(strlen($String)<=$Length){
$stringValue=$String;
} else {
$stringValues=substr($String,0,$Length) . '.';
$lengths=strrpos($stringValues,".");
$stringValue=substr($stringValus,0,$lengths).".";
}
return $stringValue;
}