回顾下PHP基础知识-字符串数组操作(php数组字符串转数组)

网友投稿 739 2022-08-29

回顾下PHP基础知识-字符串数组操作(php数组字符串转数组)

回顾下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" },注意当两个数组键值相同时,最后的会覆盖其他元素

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:luogu1064 金明的预算方案
下一篇:PHP中的服务容器与依赖注入的思想(php依赖注入)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~