PHP字符串操作

2022/8/7 1:23:57

本文主要是介绍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


这篇关于PHP字符串操作的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程