PHP字符串操作

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

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

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

// 生成a-z A-Z 0-9 组成的字符串
$codes = implode("",range('a','z')).implode("",range('A','Z')).implode("",range(0,9));$code = '';
for ($i=0; $i < 4; $i++) { // 获取随机索引数$index = mt_rand(0,strlen($codes)-1);$code .= $codes[$index];
}
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

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

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

字符串截取

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

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

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

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

// parse_str() 将字符串解析成数组
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str, $output);
extract($output);
echo $first;  // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz
$url = "id=1&name=zhang&gender=1";
parse_str($url,$result);
echo "<pre>";
print_r($result);
/*
Array
([id] => 1[name] => zhang[gender] => 1
)
*/// --------------------------------
// parse_url() 解析 URL,返回其组成部分的数组
$url = 'http://zhang.com:password@hostname/0425/demo.php?id=1&name=zhang#anchor';
echo "<pre>";
print_r(parse_url($url));
/*
Array
([scheme] => http[host] => hostname[user] => zhang.com[pass] => password[path] => /0425/demo.php[query] => id=1&name=zhang[fragment] => anchor
)*/
// 可以通过设置第二个参数来返回需要的部分
echo parse_url($url,PHP_URL_QUERY); // id=1&name=zhang
echo parse_url($url, PHP_URL_PATH); // /0425/demo.php// -------------------------------------------
// http_build_query — 生成 URL-encode 之后的请求字符串
$url = "http://zhang.com?name=张珊&age=20&email=zhang@qq.com";
$query = parse_url($url,PHP_URL_QUERY);
// name=张珊&age=20&email=zhang@qq.com
// 获取到query在通过parse_str转换为数组
parse_str($query,$params);
echo "<pre>";
print_r($params);
/*
Array
([name] => 张珊[age] => 20[email] => zhang@qq.com
)*/
// 请求参数转为Unicode
echo http_build_query($params);
// name=%E5%BC%A0%E7%8F%8A&age=20&email=zhang%40qq.com
// http_build_query参数不光可以为数组,也可以为一个对象
echo http_build_query(new class{public $name = 'admin';public $email = 'admin@php.cn';private $gender = 'male'; // 私有成员
});
// name=admin&email=admin%40php.cn

普通图片转换为bs64图片

html中输出一张图片

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


将 PHP 脚本伪装成image图片

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

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

<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

<?php$str = 'This is an encoded string';echo base64_encode($str); // 编码后的字符串数据 // VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==$file = file_get_contents('https://c-ssl.duitang.com/uploads/item/202006/20/20200620205947_kxnPk.thumb.1000_0.jpeg');$imgbs64 = base64_encode($file);echo $imgbs64; // 输出60位的散列值
?>
// 通过img标签显示bs64位的图片
<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 — 验证密码是否和散列值匹配

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

更多字符串相关函数

  1. 字符串查找

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

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

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

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

var_export(stripos('xyz', 'c'));; // 未发现将返回 false
echo stripos('ABCabc', 'c'); // 返回首次出现位置 2echo strripos('ABCabcd', 'c'); // 最后一次出现位置 5echo strpos('ABCabc','c'); // 5 区分大小写
echo strpos('ABCabc','C'); // 2echo 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文件中总结的字符串函数库,对表单字段进行验证? 比如限制密码长度,两次密码须一致, 验证码验证,用户名首位需是字母等等?

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

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

显示效果:

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

  1. python常用处理字符串函数的详细分析(全)

    目录 前言 1.split 2.join 3.strip/lstip/rstrip 4.replace 5.lower/upper/capitalize 6.其他 前言 处理字符串的一个常用模块是 s ...

  2. 视频教程-2020新版C语言程序设计零基础入门小白自学编程-C/C++

    2020新版C语言程序设计零基础入门小白自学编程 7年的开发架构经验,曾就职于国内一线互联网公司,开发工程师,现在是某创业公司技术负责人, 擅长语言有node/java/python,专注于服务端研发 ...

  3. SQLServer常用的字符串函数梳理

    今天给大家分享一下SQLServer常用的字符串函数知识笔记,希望对大家能有所帮助! 1.ASCII(字符串表达式) 作用:返回表达式最左侧字符串的ASCII代码值. 示例:SELECT ASCII( ...

  4. C语言常用的字符串函数

    C语言常用的字符串函数 以下函数都在头文件 string.h 中 (1)strcpy()字符串复制函数 函数原型:char *strcpy(char *d ,char *s) 功能:复制字符串s到字符 ...

  5. 常用:javascript字符串函数 收藏

    常用:javascript字符串函数 收藏 concat 将两个或多个字符的文本组合起来,返回一个新的字符串. var a = "hello"; var b = ",wo ...

  6. SQL 常用的字符串函数

    SQL 常用的字符串函数 1.replace:替换函数 replace(string,from_str,to_str) 即:将string中所有出现的from_str替换为to_str 2.left: ...

  7. 【php基础入门】PHP中常用的数组操作使用方法笔记整理(推荐)

    PHP数组 数组是对大量数据进行有效组织和管理的手段之一,通过数组的强大功能,可以对大量性质相同的数据进行存储.排序.插入及删除等操作,从而可以有效地提高程序开发效率及改善程序的编写方式. 数组:是一 ...

  8. MySQL数据库 学习笔记 零基础入门 面试 整理

    一.MySQL基础篇 1. 数据库技术的基本概念和方法 1.1 数据库基本概念 1] 数据 数据(Data)指对客观事物进行描述并可以鉴别的符号,这些符号是可识别的.抽象的,不仅仅指狭义上的数字,而是 ...

  9. 零基础学python pdf-笔记《零基础入门学习Python(第2版)》PDF+课件+代码分析

    通过自学编程,感觉到基础知识很重要,越到后面越能发现这一点,光记住是不行的,还要灵活运用,要多调试代码,计算机就是一个不断练习,不断遇到问题,解决问题的工种,要根据实际的业务能想到对应的语法,实际项目 ...

最新文章

  1. 教你如何处理Nginx禁止ip加端口访问的问题
  2. 互联网公装企业“inDeco领筑智造”完成A+B轮近1.1亿元融资
  3. 树莓派基于 Linux 的 Windows XP 现已可用
  4. 在ASP.NET中重写URL 方法三:在IIS7中使用HttpModule 实现无扩展名的URL重写
  5. 【Paper】2019_Distributed Optimal Control of Energy Storages in a DC Microgrid with Communication Dela
  6. bert中的sep_基于向量的深层语义相似文本召回?你需要BERT和Faiss
  7. 对数据库连接池的理解
  8. 苹果官方将首次参与天猫 618 促销活动;淘宝回应用户账号被禁用980年;Julia 1.5.0 beta1 发布 | 极客头条...
  9. Android 自定义AlertDialog类
  10. 你真的要收下这份大礼包!!
  11. SQLServer数据库基础教程
  12. android坐标画图软件下载,几何平板Geometry Pad(绘图,测量数字坐标轴)2.7.0
  13. 黑桃k游戏java实战_Java入门第三季项目实战——扑克游戏
  14. usb驱动修复_win10 1903 5月29号的质量更新修复了哪些问题?
  15. 表结构生成html页面,表结构设计器
  16. Netty权威指南 第2版
  17. Windows Server 2012 R2 安装补丁
  18. ERROR! MySQL is not running, but PID file exists
  19. java中的0x00代表什么
  20. 一些最基本的健身知识分享

热门文章

  1. 开源测试平台RunnerGo,测试工程师必备
  2. ch01: 初识数据库
  3. 面试题:找出数列中间未排序好的子数列
  4. python turtle 海龟绘图,绘制小猪佩奇
  5. jsp 登陆成功后,显示登录的用户名
  6. hbase 使用lzo_hbase 使用LZO笔记
  7. mysql管理器打不开_我安装好了MySQL.. 控制台却打不开... 有什么办法打开MySQL的控制台...
  8. opencv-python 视频抽帧成一张张图片
  9. 《新编计算机科学概论》一2.5 计算机软件系统
  10. 项目实战总结以及接入U-APM