字符串操作
字符串查找
# 查找首次出现的位置,不区分大小写 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
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/279180.html