Home  >  Article  >  Backend Development  >  Detailed explanation of function examples for splitting and merging two strings in PHP

Detailed explanation of function examples for splitting and merging two strings in PHP

怪我咯
怪我咯Original
2017-07-06 11:18:361254browse

This article mainly introduces the function of php to split and merge two strings. It analyzes the relevant skills of php for string operations with examples. Friends in need can refer to the following

The example in this article describes the function of splitting and merging two strings in PHP. Share it with everyone for your reference. The specific implementation method is as follows:

Here, two strings are divided and merged, for example, str1=aaaa, str2=bbbb, and 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
*/
is generated after merging.

The above is the detailed content of Detailed explanation of function examples for splitting and merging two strings in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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