0

重複の可能性:
PHP で文字列を短縮 (全単語のみ)

substr の下では、使用しています。データベースから最初の 38 文字をエコーし​​ます。このコードは end にある単語を壊します。

<?php echo substr(ucfirst($row['metadesc']),0,38); ?>...

このように出力されます。

news for today was null try tomo

単語の末尾から 38 文字後に文字列を停止する方法。

出力は次のようになります

news for today was null try tomorrow
4

3 に答える 3

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;
}
于 2012-07-19T11:32:29.473 に答える
0

次の正規表現を使用できます。

preg_match('/^(.{1,38})\b/u', $string, $matches);

あなたの文字列は次のようになります。

$matches[1]
于 2012-07-19T11:58:32.237 に答える
0
function substrword($str, $begin, $length) 
{
    if (($begin + $length) < strlen($str)) {    
            return substr($str, $begin, $length).current(explode(' ', substr($str, $length))).'...';
    }
    return $str;
}
于 2012-07-19T11:25:06.113 に答える