php 常用字符串处理

*连接字符串
使用.操作符
<?php
$txt1 = "hello";
$txt2 = "alice";
echo $txt1.' '.$txt2; //"hello alice"
?>


*计算字符串长度

使用strlen()函数
<?php
$txt = "hello";
echo strlen($txt);//输出5
?>

*查找字符(字符串)
使用strpos()函数,查找字符串内某个字符(字符串),并返回该字符(字符串)首字符位置索引
<?php
$sentence = "Alice like banana";
$index = strpos($sentence,'like');
echo $index;//输出6,A索引对应0
?>

*字符串替换
使用str_replace(find,replace,string,count)函数
find - 要查找的字符串
replace - 替换find的值
string - 被搜索的字符串
count - 可选,对替换数进行计数
函数返回替换后的字符串,如果没有匹配find的字符串,返回原字符串
string也可以是数组,array($string1,$string2);
 <?php
$sentence = "monster gives birth to monster";
$replace = str_replace("monster","human",$sentence,$count);
echo $replace;//human gives birth to human
echo $count;//2
?>

*字符替换
对一个字符串中某些字符进行替换,可以使用strtr(string,from,to)函数
 <?php
$sentence = "monster gives birth to monster";
$replace = strtr($sentence,"m","h");
echo $replace;//honster gives birth to honster
?>

*返回字符串的一部分
使用 substr(string,start,length)函数
start - 从字符串何处开始
length - 返回字符串的长度,未填写则返回开始处到字符串结尾
<?php
$sentence = "monster gives birth to monster";
$sub = substr($sentence, 8,5);//$sentence[8] is 'g'
echo $sub;//give
?>


*密码处理 

使用md5() sha1()计算字符串md5 SHA-1散列
<?php
echo "md5:".md5("hello");//32位
echo "sha1".sha1("hello");//40位
?>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值