Keyword conversion array php

王林
Release: 2023-05-19 14:19:38
Original
430 people have browsed it

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);
Copy after login

The output result is:

Array
(
    [0] => php
    [1] => mysql
    [2] => javascript
    [3] => css
)
Copy after login

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);
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template