php字符串函数的使用

strlen函数的使用:

  • 网页注册:
<head><meta charset="utf-8"/><title>用户注册</title></head>
<body>
<form action="index.php">
    <input type="text"name="name"value="<?=@$_GET['name']?>"placeholder="用户名至少3位"><br/>
    <input type="password"name="password"valu="<?=@$_GET['password']?>"placeholder="密码长六到十位"><br/>
    <button type="submit">提交数据</button>
</form>
</body></html>
<?php
if(!isset($_GET['name'])||!isset($_GET['password'])) {
    return;
}
$name=$_GET['name'];
$password=$_GET['password'];
if(strlen($name)<3)
{
    echo "<div style=''color:red>用户名不符合要求</div>";
}
else if(strlen($password)<6||strlen($password)>10)
{
    echo"<div style:'color:red'>密码不符合要求</div>";
}
else
{
    echo"注册成功";
}

strstr函数的使用://查找字符串中所包括的字符(stristr与之功能类似但不区分大小写)

<?php
$string='01快学PHP,零基础PHP从入门到精通';
var_dump(strstr($string,'01'));
echo"<hr/>";
var_dump(strstr($string,'PHP'));
echo"<hr/>";
var_dump(strstr($string,'php'));
echo"<hr/>";
var_dump(strstr($string,'PHP',true));//第三位默认为false,若为true则返回字符串之前的字符;

比较strstr和stristr函数执行的快慢:

<?php
$string='01快学PHP,零基础PHP从入门到精通';
$time_start=microtime(true);
for($i=0;$i<10000;$i++)
{
    strstr($string,'PHP');
}
$spend=microtime(true)-$time_start;//程序执行的时间;
echo"strstr()函数执行时间为".$spend*1000 ."毫秒<br/>";
$time_start=microtime(true);//记录当前时间
for($i=0;$i<10000;$i++)
{
    stristr($string,'PHP');
}
$spend=microtime(true);-$time_start;
echo"stristr()函数执行的时间为".$spend*1000 ."毫秒<br/>";

strpos函数的使用:(查找字符串首次出现的位置)

<?php
$string="hello world hello world";
echo strpos($string,'world').'<br/>';//从初始位置查
echo strpos($string,'world',10);//从字符串第10个位置开始查

strtr函数的使用(对字符串进行替换)

<?php
$from='abcdefghijklmnopqrstuvwxyz';
$to='asdfghjklqwertyuiopzxcm';
$string='to the world you may be one person ,but to one person you may be the world';
$security_string=strtr($string,$from,$to);
echo "加密后的句子是:<br/>".$security_string."<br/>";
上一篇:leetcode(力扣)第二十八题:实现 strStr()_C++


下一篇:算法练习之合并两个有序链表, 删除排序数组中的重复项,移除元素,实现strStr(),搜索插入位置