Home > Article > Backend Development > Keyword conversion array php
In PHP, converting keywords into arrays is a common operation. If you have some comma separated keyword strings and need to convert them to an array for better processing, this article will provide you with some solutions.
Method 1: Use the explode function
PHP has a built-in explode function, which can split a string into an array according to specified characters. By using comma as delimiter, we can convert the keyword string into an array. The sample code is as follows:
$keywords = "php, mysql, javascript, css"; $keyword_array = explode(", ", $keywords); print_r($keyword_array);
The output result is:
Array ( [0] => php [1] => mysql [2] => javascript [3] => css )
Method 2: Use preg_split function
In addition to the explode function, we can also use the preg_split function to achieve the same purpose. The preg_split function supports the use of regular expressions as separators, so we can process strings more flexibly. The sample code is as follows:
$keywords = "php, mysql, javascript, css"; $keyword_array = preg_split('/,s*/', $keywords); print_r($keyword_array);
The output result is the same as using the explode function.
Method 3: Use the strtok function
Using the strtok function can convert a string into an array more efficiently. The strtok function is a C language standard library function and is also available in PHP. We can use the strtok function to split the string one by one and replace the delimiter with null while splitting. The sample code is as follows:
$keywords = "php, mysql, javascript, css"; $delim = ","; $keyword_array = array(); $token = strtok($keywords, $delim); while ($token !== false) { array_push($keyword_array, $token); $token = strtok($delim); } print_r($keyword_array);
The output result is the same as the first two methods.
Summary
In this article, we introduced three methods to convert keyword strings into arrays. Among them, the explode and preg_split functions are more commonly used, while the strtok function is suitable for situations where high performance is required when processing large amounts of data. You can choose a suitable method according to your own situation to convert a string into an array.
The above is the detailed content of Keyword conversion array php. For more information, please follow other related articles on the PHP Chinese website!