zoukankan      html  css  js  c++  java
  • PHP substr()函数

    PHP substr()函数可以分割文字,但要分割的文字如果包括中文字符往往会遇到问题,这时可以用mb_substr()/mb_strcut这个函数,mb_substr() /mb_strcut的用法与substr()相似,只是在mb_substr()/mb_strcut最后要加入多一个参数,以设定字符串的编码,但是 一般的服务器都没打开php_mbstring.dll,需要在php.ini中把php_mbstring.dll打开。

    1
    2
    3
    <?php
    echo mb_substr('我们都是好孩子hehe',0,9);
    ?>

    输出:我们都

    现在我们加上字符集utf-8

    <?php
    echo mb_substr('我们都是好孩子hehe',0,9,'utf-8');
    ?>


    输出:我们都是好孩子he

    第一个是以三个字节为一个中文,这就是utf-8编码的特点,下面加上utf-8字符集说明,所以,是以一个字为单位来截取的

    下面是ecshop里面的截取UTF-8编码下字符串的函数

    复制代码
     1 function sub_str($str, $length = 0, $append = true)
    2 {
    3 $str = trim($str);
    4 $strlength = strlen($str);
    5
    6 if ($length == 0 || $length >= $strlength)
    7 {
    8 return $str; //截取长度等于0或大于等于本字符串的长度,返回字符串本身
    9 }
    10 elseif ($length < 0) //如果截取长度为负数
    11 {
    12 $length = $strlength + $length;//那么截取长度就等于字符串长度减去截取长度
    13 if ($length < 0)
    14 {
    15 $length = $strlength;//如果截取长度的绝对值大于字符串本身长度,则截取长度取字符串本身的长度
    16 }
    17 }
    18
    19 if (function_exists('mb_substr'))
    20 {
    21 $newstr = mb_substr($str, 0, $length, EC_CHARSET);
    22 }
    23 elseif (function_exists('iconv_substr'))
    24 {
    25 $newstr = iconv_substr($str, 0, $length, EC_CHARSET);
    26 }
    27 else
    28 {
    29 //$newstr = trim_right(substr($str, 0, $length));
    30 $newstr = substr($str, 0, $length);
    31 }
    32
    33 if ($append && $str != $newstr)
    34 {
    35 $newstr .= '...';
    36 }
    37
    38 return $newstr;
    39 }
  • 相关阅读:
    Django--URLconf
    Django--视图层
    Django 初识之安装下载以及模型目录简介
    jQuery基础
    BOM&DOM
    带你快速上手前端三剑客之css
    mysql 触发器、流程控制、事务等
    前端之html
    python中pymsql常用方法(1)
    18、设计模式-行为型模式-迭代器模式
  • 原文地址:https://www.cnblogs.com/echohao/p/5371908.html
Copyright © 2011-2022 走看看