Home > php教程 > php手册 > 实例讲解php如何分割与合并两个字符串

实例讲解php如何分割与合并两个字符串

WBOY
Release: 2018-10-24 15:51:18
Original
1256 people have browsed it

本文实例讲述了php分割合并两个字符串的函数。分享给大家供大家参考。具体实现方法如下:

这里实现把两个字符串进行分割合并,例如str1=aaaa,str2=bbbb,合并后生成abababab

/**
 * 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(&#39;&#39;, $str2);
}
//范例演示:
print MergeBetween(&#39;abcdef&#39;, &#39;__&#39;) . "\n";
print MergeBetween(&#39;__&#39;, &#39;abcdef&#39;) . "\n";
print MergeBetween(&#39;bb&#39;, &#39;aa&#39;) . "\n";
print MergeBetween(&#39;aa&#39;, &#39;bb&#39;) . "\n";
print MergeBetween(&#39;a&#39;, &#39;b&#39;) . "\n";
/*
Output:
a_b_cdef
a_b_cdef
baba
abab
ab
*/
Copy after login

希望本文所述对大家的php程序设计有所帮助。

【相关教程推荐】

1. php编程从入门到精通全套视频教程 

2. php从入门到精通  

3. bootstrap教程 

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template