PHP常用函数汇总

一、字符串函数:

1.PHP类似C#中的indexof()函数:

strpos($str,'|'); 返回位置数字 从0开始

2.格式化字符串:

var str = sprintf("需要格式的内容%s,内容2%s",变量1,变量2); %s是变量替换的内容

3.去除数组中的空字符元素:

foreach ($forbidKeyWordsArray as $key => $val)
{
    if ($val=='')
    {
        unset($forbidKeyWordsArray[$key]);
    }
}

array_filter();  //注意:如果字符为0,false,null则也会被清除  如, $str='2:0';  array_filter(explode(':',$str)); 返回的数组结果只有2,0被过滤掉了。 详细>>

详细1  详细2

 

4.正则替换:

a.常用方式:

preg_replace($pattern,$replaceString,$source);

如:$str = preg_replace( "@<script(.*?)</script>@is", "", $str );   //@是定界符 is:i表示忽略大小写,s表示空格 此函数默认为全局匹配,所以不加g  详细>>

 

b.其他方式:

ereg系列的正则表达式不需要定届符,preg系列的才需要(详解>>)。

不区分大小写正则替换:(不推荐使用:不支持非贪婪模式 正则里面出现?号则可能就出错!)
string eregi_replace ( string $pattern , string $replacement , string $string )    参数1:正则  参数2:替换成什么  3:需要处理的字符串


区分大小写正则替换:(不推荐使用:不支持非贪婪模式 正则里面出现?号则可能就出错!)
string ereg_replace ( string $pattern , string $replacement , string $string )

return preg_match('/'.$forbidKeyWords.'/i', $text); 用正则判断是否有包含的字符  // i表示忽略大小写,正则字符需要前后加上/,否则无效

5.字符串替换

a.不区分大小写:

str_ireplace(find,replace,string,count) //find:需要替换的字符 replace:需要被替换成什么字符 string:原字符串

替换普通字符串:
str_ireplace("world","John","Hello world!"); //结果:Hello John!

替换数组:
$arr = array("blue","red","green","yellow");
str_ireplace("red","pink",$arr,$i); 
结果:
Array
(
[0] => blue
[1] => pink
[2] => green
[3] => yellow
)

$i: 1 //被替换的个数

b.区分大小写:str_replace(find,replace,string,count)

 

php中几个字符串替换函数详解

 

6.用字符将字符串分隔为数组:

1.普通内置函数方式:

var arrayRes = explode('|',字符串);  详细介绍>>

 

PHP根据换行分隔字符串:
$arr = explode("\n",$Str);

 

2.正则方式:

preg_split($pattern,$subject); //通过正则分隔字符串为数组arry  详细>>

split($pattern,$string); //可以根据多个字符来分隔   详细>>

$str = 'ab,cde,|fg,hk#dd';
$array = split('[,|#]',$str);

 

7.去除空格

a.自带函数:

echo trim(" 空格 ")."<br>";  去两端空格
echo rtrim(" 空格 ")."<br>"; 去左空格
echo ltrim(" 空格 ")."<br>";  去右空格

b.正则方式:php去除字符串首尾空格(包括全角)

$str="     脚本之家 www.jb51.net     ";
$str = mb_ereg_replace('^( | )+', '', $str);
$str = mb_ereg_replace('( | )+$', '', $str);
echo mb_ereg_replace('  ', "\n  ", $str);

 

8.字符串判等更多>>

1.strcmp(string str1,string str2)函数:字符串比较 区分大小写 必须完全一致
如果 str1 小于 str2 返回 < 0; 如果 str1 大于 str2 返回 > 0;如果两者相等,返回 0。

2.strcasecmp():该函数同strcmp函数基本一致,但是该函数在比较的时候,不区分大小写.

9.计算字符串长度:strlen()与mb_strlen()区别  详细>>

UTF8编码:

strlen()1个中文长度为3  

mb_strlen('中文','utf8')1个中文长度为3

利用以上2个函数可以算出中英文混排的占位是多少(一个中文字符的占位是2,英文字符是1)。

$str ='中文a字1符';

strlen($str)值是14,mb_strlen($str)值是6,则可以计算出“中文a字1符”的占位是10.

    <?php  
    //测试时文件的编码方式要是UTF8  
    $str='中文a字1符';  
    echo strlen($str).'<br>';//14  
    echo mb_strlen($str,'utf8').'<br>';//6  
    echo mb_strlen($str,'gbk').'<br>';//8  
    echo mb_strlen($str,'gb2312').'<br>';//10  
    ?> 

 

strlen()函数处理中文:

strlen()无法正确处理中文,它得到的只是字节数。GB2312编码,strlen得到的值是汉字个数的2倍,而对于UTF-8编码的中文,就是3倍的差异了(在 UTF-8编码下,一个汉字占3个字节)。

 

截取字符串:

截取或获取中文字符串和长度用:mb_strlen();mb_substr(); //最后一个参数可以指定编码格式 参考>>

英文或数字用: strlen();substr();

 

获取内部编码:mb_internal_encoding();

注:mb_strlen并不是PHP核心函数,使用前需要确保在php.ini中加载了php_mbstring.dll,即确保“extension=php_mbstring.dll”这一行存在并且没有被注释掉,否则会出现未定义函数的问题。

 

10.字符串中是否包含特定字符串:

strstr($str,特定字符); //包含则返回true 否则返回false

 

11.Array数组中是否包含某值: 详细>>

in_array($value,$content,$type);  //如果value是字符串,而且$type=true。则搜索区分大小写

 

12.正则匹配:

1.preg_match($pattern,$subject); //$pattern:正则 $subject:源字符串  返回true则表示有匹配项(一旦发现有一个匹配的即返回)  false表示无  详细>>

2.preg_match_all($pattern,$subject,$matchArray); //全局匹配 $matchArray:所有匹配项Array   $matchArray[0]表示所有完整模式的匹配 具体项则为$matchArray[0][0]、[0][1]....  $matchArray[0]表示所有匹配到的组,类似c#中的group分组(放在()中的值)。$matchArray[1][0]、[1][1]... 更多>>     详细>>

<?php
preg_match_all("|<[^>]+>(.*)</[^>]+>|U",
    "<b>example: </b><div align=left>this is a test</div>",
    $out, PREG_PATTERN_ORDER);
echo $out[0][0] . ", " . $out[0][1] . "\n";   //输出:<b>example: </b>, <div align=left>this is a test</div>  是完整模式的
echo $out[1][0] . ", " . $out[1][1] . "\n";   //输出:example: , this is a test  是分组Group 在小括号里面的(.*)
?>

 preg_match_all的实例:(将c#代码改版为PHP)

C#写法:

string newContent = Regex.Replace(
content,
@"\s*@[^::\s]+\s*",
new MatchEvaluator(
                        delegate(Match match)
                        {   
                            //利用match.Value进行逻辑处理
                            string name = Utility.GetInnerText(match.Value.Replace("@", "").Replace("#", "").Trim());
                            if (!String.IsNullOrEmpty(name))
                            {
                                //优先关联VIP作家的作家名
                                AuthorInfo authorInfo = author.GetVipAuthorInfoByAuthorName(name).ReturnObject;
                                if (authorInfo != null && authorInfo.UserId > 0)
                                {
                                    userIdList.Add(authorInfo.UserId);
                                    return String.Format("[aid={0}]", authorInfo.AuthorId);
                                }
                                else
                                {
                                    //如果不存在该作家名的VIP作家,则再关联用户昵称
                                    long userId = user.GetUserIdByNickName(name).ReturnObject;
                                    if (userId > 0)
                                    {
                                        userIdList.Add(userId);
                                        return String.Format("[uid={0}]", userId);
                                    }
                                }
                            }
                            return match.Value;
                        }
                  ),
RegexOptions.IgnoreCase
);
View Code

PHP改版的写法:

$pattern ='/\s*@[^::\s]+\s*/i';
        preg_match_all($pattern, $content,$match);
        for ($i=0;$i<count($match[0]);$i++)
        {
            $matchStr = $match[0][$i];
            $replaceStr = $match[0][$i];
            $name = Common\Common::getInnerText($matchStr);
            if (isset($name) && $name)
            {
                //优先关联VIP作家的作家名
                $authorInfo = $author->getVipAuthorInfoByAuthorName($name)->returnObject; 
                if ($authorInfo!=null && $authorInfo->UserId>0)
                {
                    $userIdList[]=$authorInfo->UserId;
                    $replaceStr = sprintf('[aid=%s]',$authorInfo->AuthorId);
                }
                else 
                {
                    //如果不存在该作家名的VIP作家,则再关联用户昵称
                    $userId = $user->getUserIdByNickName($name)->returnObject; 
                    if ($userId>0)
                    {
                        $userIdList[]=$userId;
                        $replaceStr = sprintf('[uid=%s]',$userId);
                    }
                }
            }
            //替换
            $newContent = str_replace($matchStr, $replaceStr, $content);
        }
View Code

 

preg_match_all()常见错误:Unknown modifier '/'   

解决办法:
如果你用斜杠(/)做正则的定界符的话,如果你的表达式里出现了斜杠必须用转义,改成下面这样就可以了
$preg = "/hspace=5><a href=\"http:\/\/cn.jokes.yahoo.com\/(.*).html\" class="list" target=_blank>/isU";

总结:正则里面出现/的话 首尾的正则界定符可以用其他的,如:|,{},[]等....

 

13.判断字符串以什么开头:

1. strpos($str,"http://") === 0

2.substr($str,7) == 'http://'

 

14.字符串大小写转换:更多>>

strtoupper($str);

strtolower($str);

 

二、其他函数

1.is_numeric():

字符串数字和数字都返回true 其他返回false

 

2.获取指定范围内数组的值:详细>>

array_slice(array,offset,length,preserve);
array:数组
offset: 规定取出元素的开始位置。如果是正数,则从前往后开始取,如果是负值,从后向前取 offset 绝对值。

<?php
$a=array(0=>"Dog",1=>"Cat",2=>"Horse",3=>"Bird");
print_r(array_slice($a,1,2)); //取出下标1-2范围的数组
?>

输出:
Array ( [0] => Cat [1] => Horse )

 

3.将数组Array转换为Json格式:

json_encode($arr);

示例:

/*
* 获取返回的JSON字符串
*/
private function getReturnJsonString($resultCode, $msg)
{
    $arr = array(
            'result' => $resultCode,
            'tips' => $msg
    );
    return json_encode($arr);
}

 

4.Html实体与字符互转:

Html实体转字符:html_entity_decode() 函数。

字符转实体Html:htmlentities()

 

5.php浮点数四舍五入函数

 

 

 

站外扩展阅读:

PHP String 函数大全

PHP常用数组 字符串处理函数

 

posted @ 2014-09-10 18:05  IT浪潮之巅  阅读(254)  评论(0编辑  收藏  举报
   友情链接: 淘宝优惠券