Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:没有项目经验, 肯定用得少, 这些函数结合使用场景 会记得比较深刻
在php中,提供了非常强大的字符串函数,学会了这些函数,能够让我们在工作当中,简化很多代码。
主要用来从字符串中,分割其中的字符,起始长度为1时,是从左边,为-1时,是从右边substr($string,$start,$length);
示例
echo substr('hello the world', -5,5) , '<br>';
echo substr('hello the world', 6, 3);
输出:
world
the
统计某个子串的出现频率和次数substr_count($str, $needel, $start, $length)
示例
echo substr_count('this is a test','is'),'<br>';
echo substr_count('hello teacher good','o',5),'<br>';
echo substr_count('this is a test','is',5,9),'<br>';
输出:
2
2
1
用指定字符串将数组组装成一个字符串返回
示例
echo implode('***',['html','css','js','php']),'<br>';
echo implode('1',['html','9','99','333']),'<br>';
输出:
html***css***js***php
html191991333
使用一个字符串来分割另一个字符串,返回数组
示例
$paras = 'localhost-root-utf8-3306';
printf('<pre>%s</pre>', print_r(explode('-',$paras,4),true));
list($host,$user,$pass) = explode('-',$paras,4);
echo "$host:$user => $pass";
echo '<hr>';
输出
Array
(
[0] => localhost
[1] => root
[2] => utf8
[3] => 3306
)
localhost:root => utf8
在输出的字符串中,用一个占位符代替
示例
$site = ‘php.cn’;
//$s:字符串,$d:数值
printf(‘Hello %s’,$site);
echo ‘<br>‘;
printf(‘SELECT * FROM %s
LIMIT %d’,’staff’,25);
echo ‘<hr>‘;
输出
```php
Hello php.cn
SELECT * FROM `staff` LIMIT 25
返回字符串所用字符的信息
示例
$res = '123';
echo count_chars($res),'<br>';
输出
Array
返回一个整型字符,查找字符串首次出现的位置
示例
$res = 'hello the world';
echo strpos($res,'o'),'<br>';
输出4
单词的首字母大写
示例
$str = 'the gread wall';
echo ucwords($str),'<br>';
输出The Gread Wall
搜索字符串中的值,进行替换
示例1
$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
echo $onlyconsonants,'<br>';
输出
```php
Hll Wrld f PHP
示例2
$search = array('A','B','C','D','E');
$replace = array('B','C','D','E','F');
$subject = 'A';
echo str_replace($search,$replace,$subject),'<br>';
输出
F
示例3
$str = "Line 1\nLine 2\rLine 3\r\nLine 4\n";
echo $str,'<br>';
$order = array("\r\n","\r");
$replace = '<br>';
$newstr = str_replace($order,$replace,$str);
echo $newstr,'<br>';
输出
Line 1 Line 2 Line 3 Line 4
Line 1 Line 2
Line 3
Line 4
进行多重替换时,可能替换掉前面的值
$str = "You should eat fruits,vegetables, and fiber every day.";
$healthy = array('fruits','vegetables','fiber','pizza');
$yummy = array('pizza','beer','ice cream','book');
echo str_replace($healthy,$yummy,$str),'<br>';
输出
You should eat book,beer, and ice cream every day.
The Gread Wall
得到指定字符的ASCII
示例
$str = 'BC';
echo ord($str);
输出66
字符串函数种类比较多,老师上课已经把经常用到的函数讲了一遍,根据老师的讲解,理解起来很简单,当然还有更多的字符串函数,还需要看手册,了解他们的用法,可能以后用的很少,但是一定要知道,有这么一个东西。