Home  >  Article  >  Backend Development  >  Usage of php string splitting function explode

Usage of php string splitting function explode

怪我咯
怪我咯Original
2017-07-07 10:05:102343browse

To split a string in php, we can use the function explode(), whose prototype is as follows

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

This function has 3 parameters. The first parameter $separator sets a splitting character (string). The second parameter $string specifies the string to be operated on. The $limit parameter is optional and specifies the maximum number of substrings to split the string into.
This function returns an array consisting of split substrings.

Look at the following example to analyze a multi-line text data separated by commas.
Example 1, split string.

The code is as follows:

<?php
$this_year = 2013;
$text = <<< EOT
祝无双,F,1982,广东,普遍职员
李三兵,M,1981,河北,普通职员
赵朴秀,F,1980,韩国,项目经理
EOT;
$lines = explode("\n", $text);    //将多行数据分开
foreach ($lines as $userinfo) {
   $info = explode(",", $userinfo, 3);  //仅分割前三个数据
   $name = $info[0];
   $sex = ($info[1] == "F")? "女" : "男";
   $age = $this_year - $info[2];
   echo "姓名: $name $sex . 年龄:$age <br/>";
}
/* 输出结果是:
姓名:祝无双 女 年龄:31
姓名:李三兵 男 年龄:32
姓名:赵朴秀 女 年龄:33
*/
?>

The above code first splits the text by lines, then splits each line of string by ",", and Take the first three data for processing and analysis, then organize and output.

In addition, I will introduce to you another built-in function of PHPimplode(), which is used to connect arrays into strings.

Corresponding to the split string function is the implode() function. Its alias function is called join(). The function prototypes are as follows.
string implode(string $glue, array $pieces)
string join(string $glue, array $pieces)

The implode() or join() function can combine the elements in the array $pieces Connect with the specified character $glue.
Here is a simple example for your reference.

Example 2:

The code is as follows:

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


The above is the detailed content of Usage of php string splitting function explode. 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