在php中拆分字符串我們會用到explode或者split函數,如果我們要組合字符串就可以使用implode或使用.號直接連接了
字符組合,代碼如下:
- for($k=2;$k<5;$k++)
- {
- if(!emptyempty(${'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
- */
新聞熱點
疑難解答