天天看点

5个php常用字符函数串,PHP之十个常用字符串函数

php十个常用字符串函数

在php中,提供了非常强大的字符串函数,学会了这些函数,能够让我们在工作当中,简化很多代码。

1.substr()分割字符串

主要用来从字符串中,分割其中的字符,起始长度为1时,是从左边,为-1时,是从右边

substr($string,$start,$length);

示例

echo substr('hello the world',-5,5),'

';

echo substr('hello the world',6,3);

输出:

world

the

2.substr_count():统计子串数量

统计某个子串的出现频率和次数

substr_count($str, $needel, $start, $length)

示例

echo substr_count('this is a test','is'),'

';

echo substr_count('hello teacher good','o',5),'

';

echo substr_count('this is a test','is',5,9),'

';

输出:

2

2

1

3.implode():一维数组转字符串

用指定字符串将数组组装成一个字符串返回

示例

echo implode('***',['html','css','js','php']),'

';

echo implode('1',['html','9','99','333']),'

';

输出:

html***css***js***php

html191991333

4.explode():分割字符串

使用一个字符串来分割另一个字符串,返回数组

示例

$paras='localhost-root-utf8-3306';

printf('

%s      

',print_r(explode('-',$paras,4),true));

list($host,$user,$pass)=explode('-',$paras,4);

echo"$host:$user => $pass";

echo'

';

输出

Array

(

[0]=>localhost

[1]=>root

[2]=>utf8

[3]=>3306

)

localhost:root=>utf8

5.printf():格式化输出

在输出的字符串中,用一个占位符代替

示例

$site = ‘php.cn’;

//$s:字符串,$d:数值

printf(‘Hello %s’,$site);

echo ‘

‘;

printf(‘SELECT * FROM %s LIMIT %d’,’staff’,25);

echo ‘

‘;

输出

```php

Hello php.cn

SELECT * FROM `staff` LIMIT 25

6.cout_chars

返回字符串所用字符的信息

示例

$res='123';

echo count_chars($res),'

';

输出

Array

7.strpos()

返回一个整型字符,查找字符串首次出现的位置

示例

$res='hello the world';

echo strpos($res,'o'),'

';

输出

4

8.ucwords()

单词的首字母大写

示例

$str='the gread wall';

echo ucwords($str),'

';

输出

The Gread Wall

9.str_replace()子字符串替换

搜索字符串中的值,进行替换

示例1

$vowels=array("a","e","i","o","u","A","E","I","O","U");

$onlyconsonants=str_replace($vowels,"","Hello World of PHP");

echo $onlyconsonants,'

';

输出

```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),'

';

输出

F

示例3

$str="Line 1\nLine 2\rLine 3\r\nLine 4\n";

echo $str,'

';

$order=array("\r\n","\r");

$replace='

';

$newstr=str_replace($order,$replace,$str);

echo $newstr,'

';

输出

Line1Line2Line3Line4

Line1Line2

Line3

Line4

进行多重替换时,可能替换掉前面的值

$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),'

';

输出

You should eat book,beer, and ice cream every day.

The Gread Wall

10.ord()

得到指定字符的ASCII

示例

$str='BC';

echo ord($str);

输出

66

总结

字符串函数种类比较多,老师上课已经把经常用到的函数讲了一遍,根据老师的讲解,理解起来很简单,当然还有更多的字符串函数,还需要看手册,了解他们的用法,可能以后用的很少,但是一定要知道,有这么一个东西。