Home >Backend Development >PHP Tutorial >Conversion function between php array and string_PHP tutorial

Conversion function between php array and string_PHP tutorial

WBOY
WBOYOriginal
2016-07-20 10:59:25983browse

In PHP, if we want to convert a string into an array, we can use the functions str_split(), explode(), and preg_split(). If we want to convert the array into a string, we also have a function implode() function to directly connect the arrays. . ​

Let’s first look at converting strings into arrays

str_split()

print_r(str_split("Hello"));
?>

Array
(
[0] => H
[1] => e
[2] => l
[3] => l
[4] => o
)

explode()

$str = "Hello world. It's a beautiful day.";
print_r (explode(" ",$str));
?>

Results

Array
(
[0] => Hello
[1] => world.
[2] => It's
[3] => a
[4] => beautiful
[5] => day.
)

preg_split() function

The code is as follows Copy code
 代码如下 复制代码

$user_info = "+J+++G+++++w";
$fields = preg_split("/+{1,}/", $user_info);
while ($x < sizeof($fields)) :
print $fields[$x]. "
";
$x++;
endwhile;
?>

$user_info = "+J+++G+++++w";

$fields = preg_split("/+{1,}/", $user_info);

while ($x < sizeof($fields)) :

Print $fields[$x]. "

";

$x++;

endwhile;

?>

In summary, the functions of str_split() and explode() in PHP are the same and will not be introduced here.
 代码如下 复制代码

$array = array('a','b','c');

echo implode($array);

//结果  abc


Convert array to string

implode()

Example
The code is as follows Copy code
$array = array('a','b','c'); echo implode($array); //result abc
http://www.bkjia.com/PHPjc/445612.html
www.bkjia.com
truehttp: //www.bkjia.com/PHPjc/445612.htmlTechArticleIn php, we need to convert strings into arrays. The functions we can use include str_split(), explode(), preg_split () function, if you convert an array into a string, we also have a function implode() function...
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