Two implementation methods: 1. Use the explode() function to split the string using the specified symbol as the delimiter and convert it into an array. The syntax is "explode("specified symbol",$str)"; 2. Use the preg_split() function to split the string by matching the specified character with a regular expression and convert it into an array. The syntax is "preg_split('/specified symbol/',$str,-1,PREG_SPLIT_OFFSET_CAPTURE)".
The operating environment of this tutorial: windows7 system, PHP8 version, DELL G3 computer
php uses the specified symbol to split the string and convert it into an array, that is, Split the string on a specified symbol and pass the substrings into an array.
The first reaction when seeing this is to use the explode() function.
<?php header('content-type:text/html;charset=utf-8'); $str = 'hypertext language programming'; var_dump($str); $arr=explode(" ",$str); var_dump($arr); ?>
As you can see, we use space symbols to split the string and pass the split substrings into the array as array elements.
So what else is there besides this? In fact, the preg_split() function provided by PHP can also use specified symbols to split strings and convert them into arrays
<?php header('content-type:text/html;charset=utf-8'); $str = 'hypertext language programming 1 2'; var_dump($str); $arr=preg_split('/ /', $str, -1, PREG_SPLIT_OFFSET_CAPTURE); var_dump($arr); ?>
As can be seen, in the above example we use space symbols to split the string and convert the string into an array.
Extended knowledge: explode() and preg_split() functions
1, explode() function
explode() function can be based on string splitting character splits a string, that is, it splits a string into several substrings based on the delimiter, and then combines these substrings into an array and returns it.
explode($delimiter, $string [, $limit])
The parameter description is as follows:
2. preg_split() function
preg_split() function splits a string through a regular expression.
preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags = 0 ]] )
The parameter description is as follows:
Note: This will change each element in the returned array so that each element becomes an array consisting of the 0th element being the separated substring and the 1st element being the offset of the substring in the subject. .
Return value: Returns an array composed of substrings obtained after using $pattern to split the subject string.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to use specified symbols to split strings and convert them into arrays in PHP. For more information, please follow other related articles on the PHP Chinese website!