php string segmentation function explode instance code

  • 2020-05-30 19:41:40
  • OfStack

array explode (string $separator, string $string [, int $limit])

The function takes three arguments, and the first argument, $separator, sets one split character (string). The second parameter, $string, specifies the string to operate on. The $limit parameter is optional, specifying how many substrings to divide the string into at most.
This function returns an array of spliced substrings.

Consider the following example, which analyzes a comma-separated multi-line text data.
Example 1, splitting a string.


<?php
$this_year = 2013;
$text = <<< EOT
 I wish one like ,F,1982, guangdong , General staff 
 li 3 The soldiers ,M,1981, hebei , Ordinary staff 
 Zhao Piaoxiu ,F,1980, South Korea , The project manager 
EOT;
$lines = explode("\n", $text);    // Separate multiple rows of data 
foreach ($lines as $userinfo) {
   $info = explode(",", $userinfo, 3);  // Just before the split 3 A data 
   $name = $info[0];
   $sex = ($info[1] == "F")? " female " : " male ";
   $age = $this_year - $info[2];
   echo " Name:  $name $sex .  Age: $age <br/>";
}
/*  The output is: 
 Name: zhu matchless   female   Age: 31
 Name: li 3 The soldiers   male   Age: 32
 Name: zhao puxiu   female   Age: 33
*/
?> 

Above code, first the text is divided by lines, then each line of string is divided by ",", and take the first three data for processing and analysis, and then collate and output.

Also, php has another built-in function, implode(), which concatenates arrays into strings.

The equivalent of the split string function is the implode() function, whose alias function is called join(). The function prototypes are shown below.
string implode(string $glue, array $pieces)
string join(string $glue, array $pieces)

The implode() or join() function concatenates the elements of the array $pieces with the specified character $glue.
Here is a simple example for you to learn from.

Example 2:


<?php
$fruits = array('apple', 'banana', 'pear');
$str = implode(", ", $fruits);
echo $str;
?>


Related articles: