在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
- */
波比源码 – 精品源码模版分享 | www.bobi11.com
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需!
7. 本站源码并不保证全部能正常使用,仅供有技术基础的人学习研究,请谨慎下载
8. 如遇到加密压缩包,请使用WINRAR解压,如遇到无法解压的请联系管理员!
波比源码 » php中拆分和组合字符串函数介绍
波比源码 » php中拆分和组合字符串函数介绍