我有一个测试区,它是从数据库动态文本可能是数千字。
我想把它打断,每段写上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.

所以你能帮我找到接近函数长度的句号并打断这一段吗。

最佳答案

在这里加上句号

 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.

关于php - 句点停止后将近100个单词的php代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25382027/

10-12 04:54