上部分:PHP从入门到能用(八 · 上)正则表达式的字符串练习【10大题训练——做完就学会】
@[toc]
常用的几个函数
preg_match 执行匹配正则表达式
preg_replace 执行一个正则表达式搜索和替换,返回值为替换后的字符串
preg_split 通过一个正则表达式分隔字符串
preg_grep 返回匹配模式的数组条目
preg_quote 转义正则表达式字符,返回为转义后的字符串
第一题 【字符串替代】
如果 $str=“轻轻的我走了[逗]正如我轻轻地来[句]我挥一挥衣袖[逗]不带走一片云彩 [句]”,完成下面要求:
1) 将$str 中的“[ ]”分别用“( )”代替;
2) 将$str 中的“[逗]”用“,”代替,“[句]”用“。”代替;
1)解 >>>
<?php
$str = "轻轻的我走了[逗]正如我轻轻地来[句]我挥一挥衣袖[逗]不带走一片云彩 [句]";
$str = preg_replace('/\[/', '(', $str);
echo preg_replace('/\]/', ')', $str);
运行截图
2)解 >>>
<?php
$str = '轻轻的我走了(逗)正如我轻轻地来(句)我挥一挥衣袖(逗)不带走一片云彩 (句)';
$str = preg_replace('/(逗)/', ',', $str);
echo preg_replace('/(句)/','。',$str);
运行截图
第二题 【字符串单词第一个字母全部大写】
$str=“See What information we have on the PHP coding.cn and sharing your knowledge”
要求:
1) 将此字符串的每个单词开头的字母改写成大写;
2)以空格为分界点,将其转化为数组;然后将此数组再转化为字符串,格式为“ See-What-information-we-have-on-the-PHP-coding-cn-and-sharing-your-know ledge”;
1)解 >>>
<?php
$str = "See What information we have on the PHP coding.cn and sharing your knowledge";
$str =ucwords($str);
echo $str;
运行截图
2)解 >>>
<?php
$str = "See What information we have on the PHP coding.cn and sharing your knowledge";
$str=explode(' ',$str);
echo implode('-',$str);
运行截图
第三题 【根据学号判断专业】
创建一网页,在网页上可以显示 5 个文本框,其中每个文本框的宽度为 10 个字符,最多可输入的字符个数也为 10,当点击提交按钮后,可以显示所有学生的学号(注意:每个学生的学号之间以“,”分割,且如果输入相同的学号只显示 1 遍),然后找到 10 级计算机信息管理管理专业的学生(前缀为 1082030),将其前缀改为“10 信管”,并将他们的学号输出。
解 >>>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
input{
float:left;
width:100px
}
span{
display:block;
float:left;
}
.text{
width:fit-content;
}
</style>
</head>
<body>
<form action="" method="get">
<h4>请输入学号</h4>
<input type="number" oninput="if(value.length>10)value=value.slice(0,10)" name='k[0]'><span>-</span>
<input type="number" oninput="if(value.length>10)value=value.slice(0,10)" name='k[1]'><span>-</span>
<input type="number" oninput="if(value.length>10)value=value.slice(0,10)" name='k[2]'><span>-</span>
<input type="number" oninput="if(value.length>10)value=value.slice(0,10)" name='k[3]'><span>-</span>
<input type="number" oninput="if(value.length>10)value=value.slice(0,10)" name='k[4]'><span>-</span>
<button type="submit">提交</button>
</form