We will use the explode or split function to split strings in php. If we want to combine strings, we can use implode or use the. Sign to directly connect.
Character combination
The Code is as follows: |
Copy code |
For ($ k = 2; $ k <5; $ k ++) { If (! Empty ($ {'pfile'. $ k })) {Echo $ {'pfile'. $ k};} // equivalent to $ pfile2, $ pfile3 .......} } |
The implode () function combines array elements into a string.
Note: implode () can receive two parameter sequences. However, explode () cannot be used for historical reasons. You must ensure that the separator parameter is prior to the string parameter.
Example
The Code is as follows: |
Copy code |
<? Php $ Arr = array ('hello', 'World! ', 'Beautiful', 'day! '); Echo implode ("", $ arr ); ?> |
Output:
Hello World! Beautiful Day!
The explode () function separates strings into arrays.
Note: The limit parameter is added to PHP 4.0.1.
Note: For historical reasons, although implode () can receive two parameter sequences, explode () cannot. You must ensure that the separator parameter is prior to the string parameter.
In this example, we split the string into an array:
The Code is as follows: |
Copy code |
<? Php $ Str = "Hello world. It's a beautiful day ."; Print_r (explode ("", $ str )); ?> Output: Array ( [0] => Hello [1] => world. [2] => It's [3] => [4] => beautiful [5] => day. ) |
A good php function for splitting and merging two strings
The Code is as follows: |
Copy code |
/** * Merges two strings in a way that a pattern like ABABAB will be * The result. * * @ Param string $ str1 String * @ 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 ); } // Demo: Print MergeBetween ('abcdef', '_'). "n "; Print MergeBetween ('_', 'abcdef '). "n "; Print MergeBetween ('bb ', 'A'). "n "; Print MergeBetween ('A', 'bb'). "n "; Print MergeBetween ('A', 'B'). "n "; /* Output: A_ B _cdef A_ B _cdef Baba Abab AB */
|