php中拆分和组合字符串函数介绍
在php中拆分字符串我们会用到explode或者split函数,如果我们要组合字符串就可以使用implode或使用.号直接连接了
字符组合,代码如下:
for ( $k =2; $k <5; $k ++) { if (! empty empty (${ 'pfile' . $k })) { echo ${ 'pfile' . $k };} //那么相当于输出的是$pfile2,$pfile3.......} }implode() 函数把数组元素组合为一个字符串。
注释: implode() 可以接收两种参数顺序,但是由于历史原因,explode() 是不行的,你必须保证 separator 参数在 string 参数之前才行。
例子代码如下:
<?php $arr = array ( 'Hello' , 'World!' , 'Beautiful' , 'Day!' ); echo implode( " " , $arr ); ?> //输出:Hello World! Beautiful Day!explode() 函数把字符串分割为数组。
注释: 参数 limit 是在 PHP 4.0.1 中加入的,由于历史原因,虽然 implode() 可以接收两种参数顺序,但是 explode() 不行,你必须保证 separator参数在 string 参数之前才行。
在本例中,我们将把字符串分割为数组,代码如下:
<?php $str = "Hello world. It's a beautiful day." ; print_r ( explode ( " " , $str )); ?> //输出: Array ( [0] => Hello [1] => world. [2] => It's [3] => a [4] => beautiful [5] => day. )一个不错的php分割合并两个字符串的函数,代码如下:
/** * Merges two strings in a way that a pattern like ABABAB will be * the result. * * @param string $str1 String A * @param string $str2 String B * @return string Merged string */ function MergeBetween( $str1 , $str2 ){ // Split both strings $str1 = str_split ( $str1 , 1); $str2 = str_split ( $str2 , 1); // Swap variables if string 1 is larger than string 2 if ( count ( $str1 ) >= count ( $str2 )) list( $str1 , $str2 ) = array ( $str2 , $str1 ); // Append the shorter string to the longer string for ( $x =0; $x < count ( $str1 ); $x ++) $str2 [ $x ] .= $str1 [ $x ]; return implode( '' , $str2 ); } //范例演示: print MergeBetween( 'abcdef' , '__' ) . "n" ; print MergeBetween( '__' , 'abcdef' ) . "n" ; print MergeBetween( 'bb' , 'aa' ) . "n" ; print MergeBetween( 'aa' , 'bb' ) . "n" ; print MergeBetween( 'a' , 'b' ) . "n" ; /* Output: a_b_cdef a_b_cdef baba abab ab */查看更多关于php中拆分和组合字符串函数介绍 - php函数的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did30656