php常用方法

  在日常开发中,经常我们使用系统方法或者是自己封装的方法进行项目的开发。再此总结一下!!!

一。对于字符串截取

  1.使用mbstring扩展  (注意编码的设置

    

mb_substr($str,2,5,'utf-8');

  2.自写截取函数

function subString_UTF8($str, $start, $lenth)
{
    $len = strlen($str);
    $r = array();
    $n = 0;
    $m = 0;
    for($i = 0; $i < $len; $i++) {
        $x = substr($str, $i, 1);
        $a  = base_convert(ord($x), 10, 2);   // base_convert 在任意进制之间进行转换
        $a = substr('00000000'.$a, -8);
        if ($n < $start){
            if (substr($a, 0, 1) == 0) {
            }elseif (substr($a, 0, 3) == 110) {
                $i += 1;
            }elseif (substr($a, 0, 4) == 1110) {
                $i += 2;
            }
            $n++;
        }else{
            if (substr($a, 0, 1) == 0) {
                $r[ ] = substr($str, $i, 1);
            }elseif (substr($a, 0, 3) == 110) {
                $r[ ] = substr($str, $i, 2);
                $i += 1;
            }elseif (substr($a, 0, 4) == 1110) {
                $r[ ] = substr($str, $i, 3);
                $i += 2;
            }else{
                $r[ ] = '';
            }
            if (++$m >= $lenth){
                break;
            }
        }
    }
    return $r;
}

二。转换字符集

function charset_convert($content, $from='gbk', $to='utf-8')
{
    if(function_exists('mb_convert_encoding'))
    {
        return mb_convert_encoding ($content, $to, $from);
    }
    elseif (function_exists('iconv'))
    {
        return iconv($from, $to, $content);
    }
    else
    {
        return $content;
    }
}

三。字符串相关操作

  1)去除字符串中的空格

preg_replace('/[(xc2xa0)|s]+/','', $obj);
//返回值:  如果subject是一个数组, preg_replace()返回一个数组, 其他情况下返回一个字符串。  发生错误 返回null
原文地址:https://www.cnblogs.com/xingxia/p/substr_string.html