この方法でも目的のトリミングを実現できます。
mb_strimwidth("Hello World", 0, 10, "...");
どこ:
Hello World
: トリミングする文字列。
0
: 文字列の先頭からの文字数。
10
: トリミングされた文字列の長さ。
...
: トリミングされた文字列の末尾に追加された文字列。
これは を返しHello W...
ます。
10 は、切り捨てられた文字列 + 追加された文字列の長さであることに注意してください!
ドキュメント: http://php.net/manual/en/function.mb-strimwidth.php
単語の切り捨てを避けるには:
テキストの抜粋を提示する場合、おそらく単語の切り捨ては避けるべきです。ここで述べた以外に、切り捨てられたテキストの長さに厳しい要件がない場合はwordwrap()
、次のように切り捨てて、最後の単語も切り取らないようにすることができます。
$text = "Knowledge is a natural right of every human being of which no one
has the right to deprive him or her under any pretext, except in a case where a
person does something which deprives him or her of that right. It is mere
stupidity to leave its benefits to certain individuals and teams who monopolize
these while the masses provide the facilities and pay the expenses for the
establishment of public sports.";
// we don't want new lines in our preview
$text_only_spaces = preg_replace('/\s+/', ' ', $text);
// truncates the text
$text_truncated = mb_substr($text_only_spaces, 0, mb_strpos($text_only_spaces, " ", 50));
// prevents last word truncation
$preview = trim(mb_substr($text_truncated, 0, mb_strrpos($text_truncated, " ")));
この場合、$preview
になります"Knowledge is a natural right of every human being"
。
ライブコードの例:
http://sandbox.onlinephpfunctions.com/code/25484a8b687d1f5ad93f62082b6379662a6b4713