php专区

 首页 > php专区 > PHP应用 > php函数大全 > php中拆分和组合字符串函数介绍 - php函数

php中拆分和组合字符串函数介绍 - php函数

分享到:
【字体:
导读:
          在php中拆分字符串我们会用到explode或者split函数,如果我们要组合字符串就可以使用implode或使用 号直接连接了字符组合,代码如下:for($k=2...

php中拆分和组合字符串函数介绍

在php中拆分字符串我们会用到explode或者split函数,如果我们要组合字符串就可以使用implode或使用.号直接连接了

字符组合,代码如下:

  1. for($k=2;$k<5;$k++) 
  2.  if(!emptyempty(${'pfile'.$k})) 
  3.  { echo ${'pfile'.$k};}//那么相当于输出的是$pfile2,$pfile3.......} 

implode() 函数把数组元素组合为一个字符串。

注释:implode() 可以接收两种参数顺序,但是由于历史原因,explode() 是不行的,你必须保证 separator 参数在 string 参数之前才行。

例子代码如下:

  1. $arr = array('Hello','World!','Beautiful','Day!'); 
  2. echo implode(" ",$arr); 
  3. ?> 
  4. //输出:Hello World! Beautiful Day! 

explode() 函数把字符串分割为数组。

注释:参数 limit 是在 PHP 4.0.1 中加入的,由于历史原因,虽然 implode() 可以接收两种参数顺序,但是 explode() 不行,你必须保证 separator参数在 string 参数之前才行。

在本例中,我们将把字符串分割为数组,代码如下:

  1. $str = "Hello world. It's a beautiful day."
  2. print_r (explode(" ",$str)); 
  3. ?> 
  4. //输出: 
  5. Array 
  6. [0] => Hello 
  7. [1] => world. 
  8. [2] => It's 
  9. [3] => a 
  10. [4] => beautiful 
  11. [5] => day. 

一个不错的php分割合并两个字符串的函数,代码如下:

  1. /** 
  2.  * Merges two strings in a way that a pattern like ABABAB will be 
  3.  * the result. 
  4.  * 
  5.  * @param     string    $str1   String A 
  6.  * @param     string    $str2   String B 
  7.  * @return    string    Merged string 
  8.  */   
  9. function MergeBetween($str1$str2){ 
  10.  
  11.     // Split both strings 
  12.     $str1 = str_split($str1, 1); 
  13.     $str2 = str_split($str2, 1); 
  14.  
  15.     // Swap variables if string 1 is larger than string 2 
  16.     if (count($str1) >= count($str2)) 
  17.         list($str1$str2) = array($str2$str1); 
  18.  
  19.     // Append the shorter string to the longer string 
  20.     for($x=0; $x < count($str1); $x++) 
  21.         $str2[$x] .= $str1[$x]; 
  22.  
  23.     return implode(''$str2); 
  24. }
  25. //范例演示: 
  26. print MergeBetween('abcdef''__') . "n"
  27. print MergeBetween('__''abcdef') . "n"
  28. print MergeBetween('bb''aa') . "n"
  29. print MergeBetween('aa''bb') . "n"
  30. print MergeBetween('a''b') . "n"
  31. /* 
  32. Output: 
  33. a_b_cdef 
  34. a_b_cdef 
  35. baba 
  36. abab 
  37. ab 
  38. */ 
分享到:
PHP empty() isset() is_null() 区别与性...
PHP empty() isset() is_null() 区别与性能比较 在php中empty() isset() is_null()三个函数都是判断是否为空的情况,但是如果我个要具体的深入去了解这个三个函数发现还是有许多的区别. is_null(), empty(), isset(),这几个函数以及 == ”,== array() 会在实际操作中经常用到,因为功能很类...
PHP CURL用法详解 - php函数
PHP CURL用法详解 PHP CURL的作用对于很多应用来说有很大的用处,下面我来详细介绍php curl用法详解,有需要了解的朋友可进入参考。 PHP中的CURL函数库(Client URL Library Function) curl_close — 关闭一个curl会话 curl_copy_handle — 拷贝一个curl连接资源的所有内容和参数 curl_er...
  •         php迷,一个php技术的分享社区,专属您自己的技术摘抄本、收藏夹。
  • 在这里……