Перейти к содержимому

Как преобразовать строку в массив php

  • автор:

Cтроку в массив по разделителю в PHP: explode, str_split, strtok — что выбрать?

Для того, чтобы преобразовать строку в массив по разделителю, можно использовать функцию explode()
Необходимые параметры: разделитель и строка.

Простой пример кода из документации:

2. preg_split: разбить строку на массив по регулярному выражению

Если возможностей explode() недостаточно, то можно использовать более мощную функцию: preg_split(). Она позволяет разбить строку не по фиксированному набору символов, а по регулярному выражению.

Пример из документации:

Преобразовать строку в массив по количеству символов

Функция str_split() преобразует строку в массив, разбивая ее на элементы с заданным количеством символов. Хотите узнать как ее использовать? Посмотрите документацию.

Функция strtok(): разбиение строки на токены

Есть еще функция strtok() . Она позволит задать набор из нескольких символов-разделителей, для разделения строки по словам: читать подробнее про strok.

How To Convert PHP String to Array — Phpflow.com

Parvez Alam

In this post, we’ll learn how to convert a String to an Array in PHP. The PHP language includes functions for converting strings to arrays.

There is number of ways to convert a String to an Array in PHP. We’ll discuss explode(), preg_split() and str_split() methods with example.

Convert Strings to Arrays in PHP

PHP provides functions that convert strings to arrays. The explode() function separates a string when the specified delimeter is found. The preg split function splits a string into an array using a regular expression. The str split function divides a string into equal-length array components.

PHP string to array explode()

The explode() function is used to break a string into an array, Whereas implode function returns a string from the elements of an array.

Syntax: string join( $separator, $array) The sample example:

In the above example, I have taken a string separated by a space. We use the explode function to convert string to an array by passing a delimiter a space ( ‘ ‘) as the first argument. The second argument is the source string.

Output:

PHP string to array preg_split()

The PHP preg_split() function, like the explode function, turns strings to arrays. The primary difference is that preg_split specifies the delimiter using a regular expression.

Syntax:

preg_split(pattern, string, limit, flags)

Where parameters are:

— pattern(Required): A regular expression determining what to use as a separator.
— string(Required): The source string that is being split.
— limit(Optional): Defaults to -1.It limits the number of elements that the returned array can have.
— flags(Optional): This provide options to change the returned array using Flag(PREG_SPLIT_NO_EMPTY, PREG_SPLIT_DELIM_CAPTURE, PREG_SPLIT_OFFSET_CAPTURE).

The sample example:

In the above example, I have taken a string separated by a space. I have used “/\s+/” regular expression to split string by space.

Output:

PHP string to array using str_split()

The PHP str_split() function converts its string argument to an array with elements of equal length. You can pass a length as the second argument :

Syntax:

str_split(string $string, int $length = 1): array

Where parameters are:

— string(Required): The input string.
— length(Optional): Maximum length of the chunk.

Convert a String into an Array of Characters

Don’t know if you’re aware of this already, but you may not need to do anything (depending on what you’re trying to do).

So you can access it like an array without any faffing if you just need something simple.

You can use the str_split() function:

If you wish to divide the string into array values of different amounts you can specify the second parameter:

The above will split your string into an array in chunks of two.

There is also an optional parameter on the str_split function to split into chunks of x characters.

best you should go for » str_split() «, if there is need to manual Or basic programming,

str_split() will split into bytes, rather than characters when dealing with a multi-byte encoded string.

Use mb_str_split() instead.

GTCrais's user avatar

If you need multibyte support in an outdated version of PHP (a version below PHP7.4), then use preg_split() on an empty pattern with a unicode flag. There is no need to slow down the regex engine with a capture group.

For any versions of PHP from 7.4 or higher, just use the dedicated function mb_str_split() .

As a warning to researchers using other answers on this page, if you use square brace syntax to access characters by their offset or you use str_split() , you will get broken results when dealing with multibyte characters.

For anyone doing thorough research, I should also mention the \X (unicode version of the dot) respects newline characters by default. \X is slightly different from . without the s modifier. Demo

Convert PHP string to array — with code examples

Converting a PHP string to an array can be a useful way to manipulate and process data stored in a string.

PHP provides six functions that make it easy to convert a string to an array:

In this article, you will see how these functions can be used to convert a string to an array in PHP.

explode() function

One of the most common methods of converting a PHP string to an array is to use the explode() function.

This function takes a string and a delimiter (separator) as its arguments.

It then returns an array containing the substrings of the original string that are delimited by the specified delimiter.

For example, the following code converts a string that contains a list of names separated by commas to an array containing each individual name as an element:

The print_r result will be:

The explode() function is easy to use as you only need to pass the string and the delimiter where the string will be split into the function.

Note that in the delimiter argument, the white space after the comma is also added. This is done so that the returned array elements do not contain any white space.

str_split() function

Another function that can be used to convert a PHP string to an array is the str_split() function.

This function takes a string and an optional length argument. The return value is an array containing the individual characters of the string as elements.

Consider the example below:

In the example above, the length argument is not passed to the str_split() function, so it returned an array of individual characters.

If the optional length argument is provided, each value of the array will contain the specified number of characters.

The last value may be shorter if the given string can’t be divided evenly:

Depending on the result you want to achieve, you can adjust the length argument as required.

preg_split() function

The preg_split() function takes a regular expression and a string as its arguments.

It returns an array containing the substrings of the original string that match the specified regular expression.

This function is particularly useful when the delimiter used to separate the elements of the string is a complex pattern, such as a series of multiple characters or a regular expression.

Suppose you want to split a string by three different separators: a comma, a white space, and a semicolon.

You can use the regex /[,\s:]/ as shown below:

The output will be:

preg_match_all() function

The preg_match_all() function takes a regular expression and a string as its arguments.

The function then returns a multidimensional array containing all of the matches of the regular expression in the given string.

This function is similar to preg_split() , but instead of splitting the string and returning a single array, it returns a multidimensional array of matching substrings.

For example, suppose you have a string that contains a list of dates.

To extract all of the dates from the string, we can use the preg_match_all() function as follows:

As you can see, only the string that matches the regex pattern will be extracted by the preg_match_all() function.

str_getcsv() function

The str_get_csv() function is used to parse a CSV (Comma-Separated Values) string into an array.

This function is similar to the explode() function, but it allows for more control over the format of the string and the resulting array.

For example, suppose you have a CSV string that contains a list of names that you want to convert to an array:

Since you didn’t provide any arguments to the str_getcsv() function, it used the default delimiter (a comma) and the default enclosure (double quote) to parse the CSV string.

When your CSV uses a different delimiter, you can specify the delimiter as the second argument.

The example below shows how to split the same string but with a pipe ( | ) delimiter:

Finally, here’s a code example that you can use to load a CSV file and split its content into an array:

The code above will take the data.csv file you have and process it so that you can use the values in your PHP code.

json_decode() function

The json_decode() function is used to convert a JSON string to a PHP object or array.

To convert a JSON string to an array in PHP, you can use the following code:

The output will be:

In the example above, a JSON string is defined that contains an object with three properties: name , age , and email .

When calling the json_decode() function, you need to pass the JSON string and set the second argument to true .

The second argument is also known as the associative parameter. When set to true , the function will return an associative array. By default, the function will return an object.

The resulting array contains the properties of the original JSON object in key-value format.

This allows you to easily access and manipulate the data contained in the JSON string.

In addition to the associative parameter, the json_decode() function also accepts several other optional arguments that can be used to customize the behavior of the function.

For example, the depth parameter can be used to specify the maximum depth of the resulting array, and the options parameter can be used to specify additional options for parsing the JSON string.

For more information about the json_decode() function and its arguments, you can refer to the PHP documentation at php.net.

Conclusion

In summary, there are many different ways to convert a PHP string to an array. The appropriate solution to use will depend on the format and contents of the string, as well as the desired outcome of the conversion.

Whether you are working with simple delimiter-separated strings, complex regular expressions, or JSON and other serialized data, there is a PHP function or technique that can be used to convert the string to an array.

By using the built-in functions and techniques discussed in this article, you can easily convert a PHP string to an array and manipulate the resulting data as needed.

Also, you might want to learn how to convert an array to a string using PHP.

Take your skills to the next level ⚡️

I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!

report this ad

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *