LoginSignup
8
7

More than 5 years have passed since last update.

PHP で全角・半角入り混じった文字列を指定した文字数で html タグを除去して取得する

Last updated at Posted at 2016-01-08

1 byte とか 2 byte とかではなく、読んで時の如く、指定した文字数でキッチリカッチリ文字列をカット、HTML タグを除去した文字列を取得します。第二引数で 55 と指定した場合、キッチリカッチリ 55 文字でカットされます。

例えば、ブログの概要の表示とかで使用するイメージです

/**
 * Trims text to a certain number of words.
 * The $num_words argument will apply to the number of individual characters.
 *
 * @param string $string    Text to trim.
 * @param int    $num_words Number of words. Default 55.
 * @param string $more      Optional. What to append if $string needs to be trimmed. Default '…'.
 *
 * @return string Trimmed text.
 */
function trim_words( $string = '', $num_words = 55, $more = null ) {
    $string = strip_tags( html_entity_decode( $string ) );
    $result = $string;

    if ( ! empty( $string ) ) {
        $string   = preg_split( '//u', $string, - 1, PREG_SPLIT_NO_EMPTY );
        $original = $string;
        $string   = array_slice( $string, 0, $num_words );

        if ( count( $original ) > $num_words ) {
            if ( null === $more ) {
                $more = '…';
            }

            array_push( $string, $more );
        }

        $result = implode( '', $string );
    }

    return $result;
}
8
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7