PHPで文字を抜粋する方法を WordPress の自動抜粋機能「the_excerpt()」をたどって探してみたところ、抜粋する関数 wp_trim_excerpt に辿り着いた。この関数 wp_trim_excerpt を読むと、抜粋($text)がない場合は get_the_content で全文を取得して抜粋等をおこなっている。実際の抜粋部分の流れは以下の通り
- preg_split で空白を区切り文字に $text を抜粋文字列数+1まで分割する
- count($words) が 文字列数の制限より多い場合は
array_pop($words) で最後の文字列群を切り捨てる - implode(‘ ‘, $words) で再び区切り文字” “で結合して抜粋は完了
実際には$excerpt_moreを加える
function wp_trim_excerpt($text) {
$raw_excerpt = $text;
if ( '' == $text ) {
$text = get_the_content('');
$text = strip_shortcodes( $text );
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]>', $text);
$text = strip_tags($text);
$excerpt_length = apply_filters('excerpt_length', 55);
$excerpt_more = apply_filters('excerpt_more', ' ' . '');
$words = preg_split("/+/", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY);
if ( count($words) > $excerpt_length ) {
array_pop($words);
$text = implode(' ', $words);
$text = $text . $excerpt_more;
} else {
$text = implode(' ', $words);
}
}
return apply_filters('wp_trim_excerpt', $text, $raw_excerpt);
}
さて、これに倣って文字列数、文字数それぞれの単位で抜粋するコードを作成した。
続きを読む
