PHP字符串操作
字符串操作
字符串查找
# 查找首次出现的位置,不区分大小写 stripos(string, needle [, offset]) echo stripos("xyC", "c"); //2 # 查找首次出现的位置,区分大小写 strpos(string, needle [, offset]) echo strpos("ABCabc", "c"); //5 # 查找最后一次出现的位置,不区分大小写 strripos(string, needle, [, offset]) echo strripos("ABCabcabcABC", "c"); //11 # 查找最后一次出现的位置,区分大小写 strrpos(string, needle, [, offset]) echo strrpos("ABCabcabcABC", "c"); //8
字符串截取
# 截取字符串 substr(string,start,length) echo substr("Hello world", 6); //world echo substr("Hello world", 6, 2); //wo # 截取中文字符串 mb_substr(string, start, length, encoding编码) echo mb_substr("你好啊", 0, 2, 'utf-8'); //你好 # 去除字符串两边的空格 trim(string, charlist删除那些字符) echo " Hello"; // Hello echo trim(" Hello"); //Hello echo trim("Hello World!", "Hed!"); //llo Worl
字符串拼接
# 方式1 双引号 $a = 'hello'; $b = 'world'; echo "$a $b"; //hello world # 方式2 用'.' echo 'hello'.' world'; //hello world
字符串大小写转换
# 单词首字母大写 echo ucwords("hello world"); //Hello World # 首字母大写 ucfirst() echo ucfirst("hello world"); //Hello world # 首字母小写 lcfirst() echo lcfirst("HELLO WORLD"); //hELLO WORLD # 字母变大写 strtoupper() echo strtoupper("hello world"); //HELLO WORLD # 字母变小写 strtolower() echo strtolower("HELLO WORLD"); //hello world
字符串替换
# 字符串替换 str_replace(find查找值,replace替换值,string [,count对替换术进行计算]) echo str_replace("hello", "HELLO", "hello world"); //HELLO world
字符串重复一个字符串
# str_repeat(string, repeat) 重复一个字符串 echo str_repeat("hello!",5); //hello!hello!hello!hello!hello!
字符串随机打乱字符串
# str_shuffle(string) 随机打乱字符串 echo str_shuffle("hello!") //!lelho
字符串转数组
$arr = explode(",", "h,e,l,l,o"); print_r($arr); Array ( [0] => h [1] => e [2] => l [3] => l [4] => o )
$arr = str_split("abc"); print_r($arr); Array ( [0] => a [1] => b [2] => c )
字符串转义
# addslashes() 对预定字符转义,字符有:[单引号(’),双引号(”)、反斜杠(\)和NULL] echo addslashes("Who's"); //Who\'s # mysql_real_escape_string() 对预定字符转义,字符有:[\x00,\n,\r,\,',",\x1a] echo mysql_real_escape_string() // 参考:https://www.runoob.com/php/func-mysqli-real-escape-string.html # 注意:addslashes和mysql_real_escape_string无法防注入。 # 防注入参考文献: # https://www.jianshu.com/p/d707ff1ad1a5 # http://shiflett.org/blog/2006/jan/addslashes-versus-mysql-real-escape-string # http://zhangxugg-163-com.iteye.com/blog/1835721
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!