在平常工做中经常须要处理一些字符串或者数组,今天有时间来整理一下php
<?php
//字符串截取
$str = 'Hello World!'
substr($str,0,5);//返回'Hello'
//中文字符串截取
$str = '你好,深圳';
$result = mb_substr($str,0,2);//返回你好
//查找字符串的首次出现
$emai = "123@163.com";
$domain = strstr($email,'@');//返回‘@163.com’
$domain = strstr($email, '@','true');//返回‘123’。
//查找字符串在另外一字符串中第一次出现的位置。
$emai = "123@163.com";
strpos($emai,'@');//返回‘3' //把字符串打散为数组 $str = '你好,深圳'; $arr = explode(',',$str);//返回值为array(2) { [0]=> string(6) "你好" [1]=> string(6) "深圳" //字符串长度 $str = "Hello world"; $str1 = strlen($str);//返回11 //把字符串中的首字符转换为大写。 $str = "hello world"; $str1= ucfirst($str);//返回“Hello world” //把字符串中的首字符转换为小写。 $str = "Hello world"; $str1= lcfirst($str);//返回“hello world” //把字符串中每一个单词的首字符转换为大写。 $str = "hello world"; $str1= ucwords($str);//返回“Hello World” //反转字符串 $str = "hello world"; $str1= strrev($str);//返回“dlrow olleh” //替换字符串中的一些字符 $str = "hello world"; $str1= str_replace('world','lisa',$str);//返回“hello lisa” //字符串转换为大写 $str = "hello world"; $str1= strtoupper($str);//返回“HELLO WORLD” //字符串转换为小写 $str = "HELLO WORLD"; $str1= strtolower($str);//返回“hello world” ?>复制代码
//数组整合成字符串数组
$arr = ['aa','bb','cc'];
$str = implode(',',$arr);//输出结果“aa,bb,cc”
//数组的key值
$arr = ['aa','bb','cc'];
$aa = array_keys($arr);//输出结果array(3) { [0]=> int(0) [1]=> int(1) [2]=> int(2) }
//合并数组
$a1=array("a"=>"red","b"=>"green");
$a2=array("c"=>"blue","b"=>"yellow");
print_r(array_merge($a1,$a2));//返回array(4) { ["a"]=> string(5) "test1" [0]=> string(2) "bb" [1]=> string(2) "cc" [2]=> string(5) "test2" },注意当两个数组键值相同时,最后的会覆盖其余元素复制代码