PHP 基础教程之字符串操作



1.去除字符串首位空格和特殊字符
trim() //去除字符串左右的空格及\n,\r,\t
echo trim("|aaaaaa|","|");
输出结果为: aaaaaa

 

ltrim() //去除字符串左边的空格及\n,\r,\t
rtrim() //去除字符串右边的空格及\n,\r,\t

2.转义,还原字符串数据
转义字符: \
echo 'select * from user where name=\'PHP\'';
输出结果:select * from user where name='PHP'

addslashes()函数:在指定的预定义字符前添加反斜杠
$str="s'd";
echo addslashes($str);
输出结果为:s\'d

stripslashes();函数删除由 addslashes() 函数添加的反斜杠
echo stripslashes("Who\s John?");
输出结果:Whos John?

addcslashes(string,characters);函数在指定的字符前添加反斜杠
$str="hello";
echo addcslashes($str,o);
输出结果:hell\o

stripcslashes();函数删除由 addcslashes() 函数添加的反斜杠
echo stripcslashes("\my na\me is Kai Ji\m.");
my name is Kai Jim

3.获取字符串的长度
strlen()
echo strlen("his name is Don");
输出结果:15;

4.截取指定字符串中指定长度的字符串
substr(string,int start,[int length]);

start 如果为负,则从字符串的末尾开始截取
length 如果为负,则表示取到倒数第length个字符

5.比较字符串
strcmp(string1,string2)//区分字符的大小写
strcasecmp(string1,string2)//不区分字符的大小写
[string1和string2相等返回1,不等返回2]

6.检索字符串
strstr();函数搜索一个字符串在另一个字符串中的第一次出现
echo strstr("Hello world! it is php","world");
输出:world! it is php

7.替换字符串
str_ireplace(find,replace,string,count);函数使用新的字符串替换字符串中的另一些字符
$str="his name is Don";
echo str_ireplace('name','nickname',$str);
输出结果:his nickname is Don

substr_replace(string,replacement,start,length);函数把字符串的一部分替换为另一个字符串
string:指定要操作的原始字符串
replacement:指定替换后的新字符串
start:指定替换字符串开始的位置
length:指定返回的字符串长度

8.格式化字符串
number_format(number,decimals,decimalpoint,separator) 将数字字符串格式化
number:要格式化的数字
decimals:可选,规定多少个小数
decimalpoint:可选,规定用作小数点的字符串
separator:可选,规定用作千位分隔符的字符串


9.分割字符串
explode(separator,string,limit) 函数
separator:必需,规定在哪里分割字符串。
string:必需,要分割的字符串。
limit:可选,规定所返回的数组元素的最大数目。
$str = "Hello|world|Its a|beautiful day.";
print_r (explode("|",$str));
输出结果:
Array
(
[0] => Hello
[1] => world
[2] => Its a
[3] => beautiful day.
)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值