PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

博客列表 > 【php基础入门】小白整理PHP常用的字符串函数使用总结分析(推荐)

【php基础入门】小白整理PHP常用的字符串函数使用总结分析(推荐)

 一纸荒凉* Armani
 一纸荒凉* Armani 原创
2021年05月03日 13:03:33 1051浏览

PHP字符串操作

字符串是 PHP 中重要的数据类型之一。在 Web 开发中,很多情况下都需要对字符串进行处理和分析,通常将涉及字符串的格式化、字符串的连接与分割、字符串的比较、查找等一系列操作。用户和系统的交互也基本上是用文字来进行的,因此系统对文本信息,即字符串的处理非常重要。

  1. $str = "zhant";
  2. // 字符串可以当做数组一样通过下标访问每一个字符
  3. echo $str[0]; // z
  4. echo $str{2}; // a
  5. // 修改字符串内容
  6. $str{4} = "g";
  7. echo $str; // zhang
  8. // 一个中文的汉字占三个字节
  9. $title = "你好";
  10. // strlen返回字符串的长度
  11. echo strlen($title); // 6
  12. // 那么访问的时候,我们需要进行拼接
  13. echo $title{0}.$title{1}.$title{2}; // 你

生成一个随机的四位验证码

  1. // 生成a-z A-Z 0-9 组成的字符串
  2. $codes = implode("",range('a','z')).implode("",range('A','Z')).implode("",range(0,9));
  3. $code = '';
  4. for ($i=0; $i < 4; $i++) {
  5. // 获取随机索引数
  6. $index = mt_rand(0,strlen($codes)-1);
  7. $code .= $codes[$index];
  8. }
  9. echo "<span style='color:red'>{$code}<span>";

字符串比较、分割、替换操作

strcmp和strcasecmp字符串比较函数

strcmp:https://www.php.net/manual/zh/function.strcmp.php

strcasecmp:https://www.php.net/manual/zh/function.strcasecmp.php

  1. // 字符串比较函数 如果 str1 小于 str2 返回 < 0; 如果 str1 大于 str2 返回 > 0;如果两者相等,返回 0。
  2. // strcmp ( string $str1 , string $str2 ) : int 严格区分大小写
  3. echo strcmp('abc','ab'); // 1
  4. echo strcmp('abc','abd'); // -1
  5. echo strcmp('abc','ABC'); // 1
  6. echo strcmp('abc','abc'); // 0
  7. // 根据ASCII码逐个进行比较
  8. // -------------------------------------
  9. // strcasecmp 和上述返回值一样 但不区分大小写
  10. echo strcasecmp('abc','ABC'); // 0
  11. echo strcasecmp('abc','abc'); // 0

字符串的拆分与合并操作

implode() 数组的值转化为字符串 join()是该函数的别名: implode()

explode字符串转数组:https://www.php.net/manual/zh/function.explode.php

list() 把数组中的值赋给一组变量:https://www.php.net/manual/zh/function.list.php

  1. $study = ['html','css','js','es6','jquery','vue','react'];
  2. // 数组转字符串函数 第一个参数为分隔符 第二个参数为数组
  3. echo implode('---',$study);
  4. // html---css---js---es6---jquery---vue---react
  5. echo join(',',$study);
  6. // html,css,js,es6,jquery,vue,react
  7. // explode 字符串转换为数组
  8. $str = "html,css,js,es6,jquery,vue,react";
  9. // 以什么来拆分字符串
  10. print_r(explode(",", $str));
  11. /*
  12. Array ( [0] => html [1] => css [2] => js [3] => es6 [4] => jquery [5] => vue [6] => react )
  13. */
  14. // 第三个参数指定拆分成几个数组
  15. print_r(explode(",", $str,6));
  16. /*
  17. Array ( [0] => html [1] => css [2] => js [3] => es6 [4] => jquery [5] => vue,react )
  18. */
  19. // -------------------------
  20. // list() 将数组的值赋值给若干变量
  21. list($localhost,$username,$password,,$port) = explode(":", 'localhost:root:root:utf8:3306');
  22. echo "mysql:host={$localhost};username={$username};password={$password};port={$port}";
  23. /* mysql:host=localhost;username=root;password=root;port=3306 */
  24. // 关联数组 赋值给变量要以键值对的方式一一对应
  25. $params = ['host'=>'localhost','username'=>'root','password'=>'root'];
  26. list('host'=>$host,'username'=>$username,'password'=>$password) = $params;
  27. printf("host=%s;username=%s;password=%s",$host,$username,$password);
  28. /* host=localhost;username=root;password=root */

字符串截取

  1. // substr()字符串截取函数
  2. echo substr('abcdefg',3,2); // de
  3. echo substr('abcdefg',3); // defg
  4. echo substr('abcdefg',-3); // efg
  5. // ASCII转换函数 chr() ord() 一般用于判断用户名是否以字母开头,截取第一个字符判断其ASCII的大小范围 A 65 a 97
  6. // ASCII对照表http://c.biancheng.net/c/ascii/
  7. // ucfirst 将首字母转换为大写
  8. // ord() 字符串转ASCII码
  9. // chr() ASCII码转字符
  10. $username = 'admin';
  11. echo ord(substr(ucfirst($username),0,1))>=65 && ord(substr(ucfirst($username),0,1))<=90?'用户名正确':'用户名请以字母开头';
  12. echo strlen($username)<4||strlen($username)>10?'用户名长度需为6-10个字符':'用户名正确';

字符串替换函数(敏感词转义)

str_replace() 子字符串替换:https://www.php.net/manual/zh/function.str-replace.php

  1. // 将window系统的目录分割符替换为Linux目录分隔符
  2. $path = "D:\phpstudy_pro\Extensions\php\php7.3.9nts\php.exe";
  3. // 查看当前操作系统支持的路径分隔符
  4. echo DIRECTORY_SEPARATOR;
  5. // 需要替换的字符内容 替换后的字符内容 字符串
  6. echo str_replace('\\','/',$path);
  7. /* D:/phpstudy_pro/Extensions/php/php7.3.9nts/php.exe */
  8. // 第四个参数可以接收替换的次数
  9. echo str_replace('转账','***','支持微信大额转账,支付宝转账,银行卡转账',$count);
  10. // 支持微信大额***,支付宝***,银行卡***
  11. echo "\'转账\'敏感词出现次数:{$count}";
  12. // 第一个参数 需要替换的字符内容可以是一个数组
  13. $vowels = array("赌博","美女",'发牌','澳门');
  14. echo str_replace($vowels, "**", "欢迎访问赌博平台,澳门皇冠赌博网站,美女在线发牌");
  15. // 欢迎访问**平台,**皇冠**网站,**在线**
  16. // 敏感词和替换内容都可以为数组,将替换为对应的内容
  17. $search = ['交友','广告','转账','直播','带货','陪聊','异性'];
  18. $flag = ['***','---','&&&','000','*货*','聊天','同性'];
  19. $news = '本公司承接各类广告代理,提供直播和带货教学服务,提供异性交友在线陪聊服务……';
  20. echo str_replace($search,$flag,$news);
  21. /* 本公司承接各类---代理,提供000和*货*教学服务,提供同性***在线聊天服务…… */

URL链接解析函数

parse_str() 将字符串解析成数组

https://www.php.net/manual/zh/function.parse-str.php

parse_url() 解析 URL,返回其组成部分的数组

https://www.php.net/manual/zh/function.parse-url.php

http_build_query 生成URL_encode之后的请求字符串

https://www.php.net/manual/zh/function.http-build-query.php

  1. // parse_str() 将字符串解析成数组
  2. $str = "first=value&arr[]=foo+bar&arr[]=baz";
  3. parse_str($str, $output);
  4. extract($output);
  5. echo $first; // value
  6. echo $arr[0]; // foo bar
  7. echo $arr[1]; // baz
  8. $url = "id=1&name=zhang&gender=1";
  9. parse_str($url,$result);
  10. echo "<pre>";
  11. print_r($result);
  12. /*
  13. Array
  14. (
  15. [id] => 1
  16. [name] => zhang
  17. [gender] => 1
  18. )
  19. */
  20. // --------------------------------
  21. // parse_url() 解析 URL,返回其组成部分的数组
  22. $url = 'http://zhang.com:password@hostname/0425/demo.php?id=1&name=zhang#anchor';
  23. echo "<pre>";
  24. print_r(parse_url($url));
  25. /*
  26. Array
  27. (
  28. [scheme] => http
  29. [host] => hostname
  30. [user] => zhang.com
  31. [pass] => password
  32. [path] => /0425/demo.php
  33. [query] => id=1&name=zhang
  34. [fragment] => anchor
  35. )
  36. */
  37. // 可以通过设置第二个参数来返回需要的部分
  38. echo parse_url($url,PHP_URL_QUERY); // id=1&name=zhang
  39. echo parse_url($url, PHP_URL_PATH); // /0425/demo.php
  40. // -------------------------------------------
  41. // http_build_query — 生成 URL-encode 之后的请求字符串
  42. $url = "http://zhang.com?name=张珊&age=20&email=zhang@qq.com";
  43. $query = parse_url($url,PHP_URL_QUERY);
  44. // name=张珊&age=20&email=zhang@qq.com
  45. // 获取到query在通过parse_str转换为数组
  46. parse_str($query,$params);
  47. echo "<pre>";
  48. print_r($params);
  49. /*
  50. Array
  51. (
  52. [name] => 张珊
  53. [age] => 20
  54. [email] => zhang@qq.com
  55. )
  56. */
  57. // 请求参数转为Unicode
  58. echo http_build_query($params);
  59. // name=%E5%BC%A0%E7%8F%8A&age=20&email=zhang%40qq.com
  60. // http_build_query参数不光可以为数组,也可以为一个对象
  61. echo http_build_query(new class{
  62. public $name = 'admin';
  63. public $email = 'admin@php.cn';
  64. private $gender = 'male'; // 私有成员
  65. });
  66. // name=admin&email=admin%40php.cn

普通图片转换为bs64图片

html中输出一张图片

  1. <img src='https://c-ssl.duitang.com/uploads/item/202006/20/20200620205947_kxnPk.thumb.1000_0.jpeg' alt='美女' width="300">


将 PHP 脚本伪装成image图片

  1. // 伪装响应请求头
  2. header('content-type:image/jpg');
  3. // 打开文件
  4. $file = file_get_contents('https://c-ssl.duitang.com/uploads/item/202006/20/20200620205947_kxnPk.thumb.1000_0.jpeg');
  5. echo $file;
  6. // 由于设置了响应头,当前脚本只能解析图片,html标签中可以通过链接该文件路径,从而显示图片内容

这样可以在html中通过img标签链接该脚本显示图片

  1. <img src="http://zhang.com/0430/demo.php" width="300">

将图片进行base64编码处理

base64_encode(): 使用 MIME base64 对数据进行编码

https://www.php.net/manual/zh/function.base64-encode.php

base64_decode():对使用 MIME base64 编码的数据进行解码

https://www.php.net/manual/zh/function.base64-decode.php

  1. <?php
  2. $str = 'This is an encoded string';
  3. echo base64_encode($str); // 编码后的字符串数据
  4. // VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==
  5. $file = file_get_contents('https://c-ssl.duitang.com/uploads/item/202006/20/20200620205947_kxnPk.thumb.1000_0.jpeg');
  6. $imgbs64 = base64_encode($file);
  7. echo $imgbs64; // 输出60位的散列值
  8. ?>
  9. // 通过img标签显示bs64位的图片
  10. <img src="data:image/jpeg;base64,<?=$imgbs64 ?>" width="300">

图中我们可以看出,经过bs64编码处理的图片链接超级长,且用户无法获取图片真实的链接

字符串散列处理

md5() 返回32位散列值

https://www.php.net/manual/zh/function.md5.php

sha1() 返回40位散列值

https://www.php.net/manual/zh/function.sha1.php

由于以上函数依赖的算法已不足够复杂,不推荐使用对明文密码加密

password_hash — 创建密码的散列(推荐)

password_verify — 验证密码是否和散列值匹配

  1. // md5() 和sha1() 由于是有机可循的,我们可以对其进行加盐处理
  2. $salt = 'zhangshuai';
  3. echo sha1('root'.$salt);
  4. // 43f5582e40049d275977f9ed76c8972723e9b4b5
  5. // --------------------------------------------
  6. // password_hash 创建密码的散列
  7. $pwd = password_hash('zhang',PASSWORD_DEFAULT);
  8. echo $pwd; // 返回 60 个字符的字符串
  9. // password_verify — 验证密码是否和散列值匹配
  10. echo password_verify('zhang',$pwd)?'密码正确':'密码错误';
  11. // ------------------------------------------
  12. // md5_file() 对文件进行散列处理
  13. // 生成md5进行存储文件中
  14. $file_md5 = md5_file('demo.php');
  15. file_put_contents('md5file.txt',$file_md5);
  16. // 在另一个PHP文件中进行验证,当demo.php被修改时,无法与文件中存储的md5进行匹配
  17. if(md5_file('demo.php') === file_get_contents('md5file.txt')){
  18. echo "文件是安全的没有被恶意篡改";
  19. }else{
  20. echo "警告!文件已被篡改";
  21. }

更多字符串相关函数

  1. 字符串查找

stripos() 用来查找字符串中某部分字符串首次出现的位置(不区分大小写)

strripos() 用来计算指定字符串在目标字符串中最后一次出现的位置(不区分大小写)

strpos() 用来查找字符串首次出现的位置

strrpos() 用来查找字符串中最后一次出现的位置

  1. var_export(stripos('xyz', 'c'));; // 未发现将返回 false
  2. echo stripos('ABCabc', 'c'); // 返回首次出现位置 2
  3. echo strripos('ABCabcd', 'c'); // 最后一次出现位置 5
  4. echo strpos('ABCabc','c'); // 5 区分大小写
  5. echo strpos('ABCabc','C'); // 2
  6. echo strrpos('ABCcabcAb','c'); // 6
  1. strtoupper与 strtolower字符串大小写转换
  2. str_ireplace() 和 str_replace() 字符串替换
  3. substr()与mb_substr():截取字符串
  4. trim():去除字符串两边的空格
  5. strlen()与mb_strlen():获取字符串长度
  6. addslashes()和stripslashes():字符串转义与还原
  7. str_repeat():重复一个字符串
  8. str_shuffle():随机打乱字符串

PHP测试题答案

1-5:C ABD D C A

6-10:AD D B C A

11-15:A B ACD D A

16-20:B A D A B

21-23:C B C

作业内容:完成一个用户注册页面, 用xmind文件中总结的字符串函数库,对表单字段进行验证? 比如限制密码长度,两次密码须一致, 验证码验证,用户名首位需是字母等等?

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>用户注册页面</title>
  6. <link rel="stylesheet" type="text/css" href="css/regist.css">
  7. </head>
  8. <body>
  9. <div class="wrapper">
  10. <article>
  11. <h1><span>个人博客注册</span></h1>
  12. <div class="main">
  13. <form action="" method="post"onsubmit="return false">
  14. <div class="tel">
  15. <input type="email" name="email" placeholder="请输入邮箱" id="telephone" required >
  16. </div>
  17. <div class="userName">
  18. <input type="text" name="userName" placeholder="请输入用户名" id="username" required>
  19. </div>
  20. <div class="password">
  21. <input type="password" name="pwd" placeholder="请输入密码" id="pwd" required>
  22. </div>
  23. <div class="againpwd">
  24. <input type="password" name="cpwd" placeholder="请再次输入密码" id="cmpwd" required>
  25. </div>
  26. <div class="captcha">
  27. <input type="text" name="captcha" id="captcha" placeholder="请输入验证码" required>
  28. <img width="60" height="37" onclick="this.src='gd_captcha.php?'+new Date().getTime();" style="margin: 10px auto;vertical-align: bottom;" src="gd_captcha.php">
  29. <em id="captchainfo">提示信息……</em>
  30. </div>
  31. <button>注册</button>
  32. </form>
  33. </div>
  34. </article>
  35. </div>
  36. <script type="text/javascript" src="js/reg.js"></script>
  37. </body>
  38. </html>
  1. /* 登录页面样式 regist.css */
  2. *{ margin: 0;padding: 0;font-family: 微软雅黑;}
  3. em{display: block;font-style: normal;font-size: 14px;color:red}
  4. li{list-style: none;display: inline-block;}
  5. li a{text-decoration: none;}
  6. html,body,.wrapper{
  7. width: 100%;
  8. height: 100%;
  9. overflow: hidden;
  10. }
  11. .wrapper{
  12. background: url(http://zhsh520.com/hero-bg.jpg);
  13. background-size: 100% 100%;
  14. position: relative;
  15. }
  16. article{
  17. width: 1200px;
  18. margin: 0 auto;
  19. }
  20. article{
  21. width: 400px;
  22. margin: 100px auto 0px auto;
  23. }
  24. article h1{width: 400px;color: #fff;text-align: center;margin-bottom: 15px;font-weight: normal;}
  25. article h1 em{display: inline-block;color:#5593ce;font-size: 25px;}
  26. .main{
  27. padding: 40px 0px;
  28. width: 100%;
  29. background-color: rgba(0, 0, 0, 0.6);
  30. }
  31. form{
  32. width: 297px;
  33. margin: 0 auto;
  34. }
  35. .main form input{
  36. margin: 10px 0;
  37. width: 280px;
  38. height: 35px;
  39. border-radius: 3px;
  40. display: inline-block;
  41. border: 1px solid rgb(165, 161, 161);
  42. padding-left: 10px;
  43. }
  44. .main form input[name="captcha"]{
  45. width: 200px;
  46. }
  47. form button{width: 290px;height: 35px;background-color: red;color: #fff;border:none;margin-top: 15px;letter-spacing: 10px;font-size: 16px;text-align: center;}
  48. footer{
  49. width: 100%;
  50. position: absolute;
  51. left: 0;
  52. bottom: 50px;
  53. font-size: 14px;
  54. color: #5593ce;
  55. }
  56. footer ul{width: 570px;height: 35px;}
  57. footer p{width: 100%;text-align: center;}
  58. footer ul li{display: inline-block;width: 90px;height: 13px;line-height: 13px;border-right: 1px solid #5593ce;text-align: center; }
  59. footer ul li a{font-size: 14px;color:#5593ce; }
  60. footer ul,footer p{margin: 0 auto;}
  1. // 提交信息验证 reg.js
  2. document.querySelector('button').addEventListener("click",function(e){
  3. const formdata = new FormData(document.querySelector('form'));
  4. const xhr = new XMLHttpRequest();
  5. xhr.open("post", "regist_check.php");
  6. xhr.onload = () => {
  7. let json = JSON.parse(xhr.response);
  8. if(json.status==0){
  9. document.querySelector("#captchainfo").textContent = json.msg;
  10. document.querySelector("#captchainfo").style.color = "red";
  11. }else{
  12. document.querySelector("#captchainfo").textContent = json.msg;
  13. document.querySelector("#captchainfo").style.color = "green";
  14. setTimeout(()=>{
  15. window.location.href = "http://baidu.com";
  16. },2000)
  17. }
  18. };
  19. xhr.send(formdata);
  20. });
  21. document.querySelector('#captcha').addEventListener('blur',function(e){
  22. // console.log(e.target.value);
  23. const xhr = new XMLHttpRequest();
  24. xhr.open("post", "captcha_check.php");
  25. xhr.onload = () => {
  26. let json = JSON.parse(xhr.response);
  27. if(json.status==0){
  28. document.querySelector("#captchainfo").textContent = json.msg;
  29. document.querySelector("#captchainfo").style.color = "red";
  30. e.target.focus();
  31. }else{
  32. document.querySelector("#captchainfo").textContent = json.msg;
  33. document.querySelector("#captchainfo").style.color = "green"
  34. }
  35. };
  36. xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
  37. xhr.send("captcha="+e.target.value);
  38. })
  1. // 用户信息验证 regist_check.php
  2. <?php
  3. session_start();
  4. $user = $_POST;
  5. if(strlen($user['userName'])<4 || !preg_match("/^[A-Za-z]/i",$user['userName']) ){
  6. echo json_encode(['status'=>0,'msg'=>'用户名长度需不小于四位且以字母开头']);
  7. }else if(strcmp($user['pwd'],$user['cpwd'])!== 0){
  8. echo json_encode(['status'=>0,'msg'=>'两次密码输入不一致']);
  9. }else if(strcasecmp($_SESSION["captcha"],$user["captcha"])!== 0){
  10. echo json_encode(['status'=>0,'msg'=>'验证码不正确']);
  11. }else{
  12. echo json_encode(['status'=>1,'msg'=>'注册成功,请稍后……']);
  13. }
  14. ?>
  1. // 验证码的验证 captcha_check.php
  2. <?php
  3. /**
  4. * 接受用户登陆时提交的验证码
  5. */
  6. session_start();
  7. //1. 获取到用户提交的验证码
  8. $captcha = $_POST["captcha"];
  9. //2. 将session中的验证码和用户提交的验证码进行核对,当成功时提示验证码正确,并销毁之前的session值,不成功则重新提交
  10. if(!empty($captcha) && strtolower($_SESSION["captcha"]) === strtolower($captcha)){
  11. echo json_encode(['status'=>1,'msg'=>'验证码正确']);
  12. }else{
  13. echo json_encode(['status'=>0,'msg'=>'验证码不正确']);
  14. }
  1. // 验证码生成 gd_captcha.php
  2. <?php
  3. session_start();
  4. $image = imagecreatetruecolor(100, 30);
  5. $bgcolor = imagecolorallocate($image, 255, 255, 255);
  6. imagefill($image, 0, 0, $bgcolor);
  7. $content = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  8. $captcha = "";
  9. for ($i = 0; $i < 4; $i++) {
  10. // 字体大小
  11. $fontsize = 10;
  12. // 字体颜色
  13. $fontcolor = imagecolorallocate($image, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120));
  14. // 设置字体内容
  15. $fontcontent = substr($content, mt_rand(0, strlen($content)), 1);
  16. $captcha .= $fontcontent;
  17. // 显示的坐标
  18. $x = ($i * 100 / 4) + mt_rand(5, 10);
  19. $y = mt_rand(5, 10);
  20. // 填充内容到画布中
  21. imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor);
  22. }
  23. $_SESSION["captcha"] = $captcha;
  24. //4.3 设置背景干扰元素
  25. for ($$i = 0; $i < 200; $i++) {
  26. $pointcolor = imagecolorallocate($image, mt_rand(50, 200), mt_rand(50, 200), mt_rand(50, 200));
  27. imagesetpixel($image, mt_rand(1, 99), mt_rand(1, 29), $pointcolor);
  28. }
  29. //4.4 设置干扰线
  30. for ($i = 0; $i < 3; $i++) {
  31. $linecolor = imagecolorallocate($image, mt_rand(50, 200), mt_rand(50, 200), mt_rand(50, 200));
  32. imageline($image, mt_rand(1, 99), mt_rand(1, 29), mt_rand(1, 99), mt_rand(1, 29), $linecolor);
  33. }
  34. //5.向浏览器输出图片头信息
  35. header('content-type:image/png');
  36. //6.输出图片到浏览器
  37. imagepng($image);

浏览地址:http://easys.ltd/regist/regist.html

显示效果:

上一条: 吉他调音器的使用方法 下一条: 0323作业
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议