1,preg_split()函数将字符串按照某元素分割,分割后结果以数组方式返回。
php中explode()可以实现此功能。array explode(string $pattern,string $str, int $limit)
<?php // 示例 1 $pizza = "piece1 piece2 piece3 piece4 piece5 piece6" ; $pieces = explode ( " " , $pizza ); echo $pieces [ 0 ]; // piece1 echo $pieces [ 1 ]; // piece2 // 示例 2 $data = "foo:*:1023:1000::/home/foo:/bin/sh" ; list( $user , $pass , $uid , $gid , $gecos , $home , $shell ) = explode ( ":" , $data ); echo $user ; // foo echo $pass ; // * ?>
implode()函数将数组转化为字符串,string implode(string $pattern,array $pieces)
<?php $array = array( 'lastname' , 'email' , 'phone' ); $comma_separated = implode ( "," , $array ); echo $comma_separated ; // lastname,email,phone // Empty string when using an empty array: var_dump ( implode ( 'hello' , array())); // string(0) "" ?>
2,preg_replace()函数的替代函数是str_replace()
mixed str_replace(string $occurrence,mixed $replacement,mixed $str),$occurrence替换字符串,$replacement待替换字符串。
如:
<?php $author ="jason@example.com"; $author = str_replace("@","(at)",$author); echo $author; ?>
输出:
jason(at)example.com
还有字符替换函数,substr_replace()函数将字符串中一部分用另一个字符串替换,替换从指定的sart位置开始,直到start+length结束。其形式为:
string substr_replace(string $str,string $replacement,int $start,int $length),$str为原字符串,$replacement为替换后的字符串,$start开始,$length长度。
如果$start为正,则$replacement从$start位置开始;
如果$start为负,则$replacement从($str长度-$start)开始;
如果给出$length为正,则$replacement的长度将是$length个字符;
如果给出$length为负,则$replacement将在($str-$length)个字符时结束;
如:
<?php $ccnumber = "1234567899991111"; echo substr_replace($ccnumber,"***************",0,12); ?>
输出:
***************1111