0

私はテキストを制限するこの関数を持っています、例えば上記のように50文字にしましょう:

$bio = limit_text($bio, 50);

function limit_text($text, $length){ // Limit Text
    if(strlen($text) > $length) {
        $text = substr($text, 0, strpos($text, ' ', $length));
    }
    return $text;
}

これは次のようなものをエコーするはずです:

こんにちは、これは50文字に制限されたテキストであり、すばらしいです...

問題は、関数がプロに見えない最後の句読点を表示することです。この例のように:

こんにちは、これは50文字に制限されたテキストで、最後にカンマがあります...

関数に最後の句読点を表示させない方法はありますか?

ありがとうございました!

4

4 に答える 4

0
<?php

$text="Hello, this is a text limited to 50 chars and it has a comma at the end.";

//$text = preg_replace("/[^a-zA-Z 0-9]+/", " ", $text); //bad
$text=rtrim($text,",.;:- _!$&#"); // good select what you want to remove


echo $text;
于 2012-06-07T00:07:35.187 に答える
0

これで作業が完了ctype_punctし、指定された文字列内の英数字以外のすべての文字がチェックされます。

function limit_text($text, $length){ // Limit Text
    if(strlen($text) > $length) {
        $text = substr($text, 0, strpos($text, ' ', $length));
        if(ctype_punct(substr($text,-1))
            $text=substr($text,0,-1);
    }
    return $text;
}
于 2012-06-07T00:08:11.793 に答える
0
return rtrim($text, ',') . '...'; // That is if you only care about the ',' character 
于 2012-06-07T00:08:42.557 に答える
-1

次のような関数を使用して、$text最初の関数を解析できます。

$text = preg_replace("/[^a-zA-Z 0-9]+/", " ", $text);
于 2012-06-07T00:04:30.993 に答える