ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

PHP字符串操作

2022-08-06 19:17:23  阅读:595  来源: 互联网

标签:Hello string echo world 字符串 操作 PHP hello


字符串操作

字符串查找

# 查找首次出现的位置,不区分大小写 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

标签:Hello,string,echo,world,字符串,操作,PHP,hello
来源: https://www.cnblogs.com/xiao-linxin/p/16557730.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有