wordPress中文截取的函数介绍
很多朋友直接使用php substr函数截取中文是会出现乱码,下面我先来给各位总结中文字符截取的函数,然后以wordpress截取中文标题为例给大家介绍实例应用.
中文截取函数, 代码如下:
function utf8_trim( $str ) { $len = strlen ( $str ); for ( $i = strlen ( $str )-1; $i >=0; $i -=1){ $hex .= ‘ ‘.ord( $str [ $i ]); $ch = ord( $str [ $i ]); if (( $ch & 128)==0) return ( substr ( $str ,0, $i )); if (( $ch & 192)==192) return ( substr ( $str ,0, $i )); } return ( $str . $hex ); } function mul_excerpt ( $excerpt , $excerpt_length ) { $myexcerpt = substr ( $excerpt ,0, $excerpt_length ); return utf8_trim( $myexcerpt ) . ‘… ‘; }或者这样也可以
//自动截断不乱码 // jieduan luanma ///////////////// function Limit_Char( $max_char = 200, $more_text = '...' , $more_link_text = '' , $limit_type = 'content' ) { if ( $limit_type == 'title' ) { $limiter = get_the_title(); } else { $limiter = get_the_content(); } $limiter = apply_filters( 'the_content' , $limiter ); $limiter = strip_tags ( str_replace ( ']]>' , ']]>' , $limiter )); if ( strlen ( $limiter ) > $max_char ) { $limiter = substr ( $limiter , 0, $max_char +1); $limiter = utf8_conver( $limiter ); echo $limiter ; echo $more_text ; if ( $more_link_text != '' ) { echo ' ' . $more_link_text . '' ; } } else { echo $limiter ; } } function utf8_conver( $str ) { $len = strlen ( $str ); for ( $i = strlen ( $str )-1; $i >=0; $i -=1){ $hex .= ' ' .ord( $str [ $i ]); $ch = ord( $str [ $i ]); if (( $ch & 128)==0) return ( substr ( $str ,0, $i )); if (( $ch & 192)==192) return ( substr ( $str ,0, $i )); } return ( $str . $hex ); }截取中文标题, 代码如下:
echo '</p><p>'. mb_substr(get_the_title(),0,18,"utf8")."..." .'</p></li>';
这样会出现乱码的,我在functions.php加入上面的中文截取代码,然后在想要截取标题的位置,添加get_short_title(),目的就达到,详细代码如下:
echo '<li><a href="' . get_permalink() . '">' ; get_short_title(18); echo '</a><data>' . get_the_time( 'n月j日' ) . '</data></li>' ;当然,其他地方这样调用也可以,代码如下:<?php get_short_title(); ?>
查看更多关于wordPress中文截取的函数介绍 - WordPress的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did8629