PHP探索之旅—-字符串String

来源:互联网 发布:淘宝的一件代发是怎么 编辑:程序博客网 时间:2024/05/17 04:20

PHP探索之旅—-字符串String

1、字符串去除空格和特殊字符

class StringOperate{public static function str_trim($str,$code){    return trim($str,$code);}   public static function str_ltrim($str,$code){    return ltrim($str,$code);}public static function str_rtrim($str,$code){    return rtrim($str,$code);}}$str = 'laravel';$code = 'l';$operate = new StringOperate();// 去除字符串左右两边空格和特殊字符$result = $operate->str_trim($str, $code);$result = 'arave';// 去除字符串左边空格和特殊字符$left = $operate->str_ltrim($str, $code);$left = 'aravel';// 去除字符串右边空格和特殊字符$right = $operate->str_rtrim($str, $code);$right = 'larave';

2、字符串转义和还原

$str = "lara'vel";// 转义$result1 = addslashes($str);$result1 = "lara\'vel";// 还原$result2 = stripslashes($result1);$result2 = "lara'vel";

3、字符串比较

$str1 = "ABC";$str2 = "abc";// 区分大小写$result = strcmp($str1, $str2);$result = "-1";// 不区分大小写$result = strcasecmp($str1, $str2);$result = "0";

4、字符串检索

$str = "abcdcbda";//查找关键字$result = strstr($str, "d");$result = "dcbda";//检索字符在字符串中出现次数$result = substr_count($str, "d");$result = "2";

5、字符串替换

$subject = "abc,sss";$search = ",sss";$replace = "def";// 替换字符串$result = str_ireplace($search, $replace, $subject);$result = str_replace($search, $replace, $subject);$result = "abcdef";

6、字符串分割和合成

$str = "a,b,c,d,e,f";//分割字符串$array = explode(",", $str); $array = "Array ( [0] => a [1] => b [2] => c [3] => d [4] => e [5] => f )";//合成字符串$result = implode(",", $array);$result = "a,b,c,d,e,f";

7、格式化字符串

$int = 123456789;//格式化字符串number_format($int); //结果:123,456,789number_format($int,3); //结果:123,456,789.000

8、截取字符串

$str = "abcdef";//截取字符串substr($str, 1); //结果:bcdefsubstr($str, -1); //结果:f
原创粉丝点击