Explode string to array in php

PHP explode: Splitting strings into arrays

In this tutorial, we look at the PHP explode function. We take a close look at its parameters, return values and it’s limitations.

Table of Contents — PHP foreach:

PHP explode — What is explode in PHP?

PHP explode() is a built-in function that is used to split a string into a string array. It splits a string based on a specified separator that we pass as an argument.

Apart from this functionality, the explode method also has a third parameter, “limit” that can be used to manipulate the number of elements in the array. We take a closer look at this below.

Syntax of PHP explode:

explode(separator,string,limit) 

Parameters:

  1. Separator — Required, used to specify where the string should be split
  2. String — Required, the string that you want to split
  3. Limit — Optional, used to specify the number of elements in the string array.
    • Positive Value — If a positive value is passed as a parameter, it denotes the number of elements the string array should contain. In case the value is lesser than the number of elements in the array, the N-1th element of the string array would contain all the remaining elements.
    • Negative Value — If a negative value is passed the last element will be trimmed off and the and the remaining part of elements would be returned as an array.
    • Zero — If zero is passed the element will contain only elements which would be the entire string.

Return Value:

If no limit argument is passed the string array would contain all the elements split by the separator. If a limit value is passed, the return values would be based on that.

Code & Explanation:

The output of the above code snippet would be:

Array ( [0] => Hire, [1] => Freelance [2] => Developers ) 

In the above code block, since a limit was not passed the returned array contains a string with all the elements.

Now let’s look at an example using the limit:

The output of the above code snippet would be:

Array ( [0] => Hire, [1] => the [2] => top Freelance Developer ) Array ( [0] => Hire, [1] => the [2] => top [3] => freelance ) 

In the first array, since the limit value was less than the number of elements all the remaining elements were passed in the last element.

In the last array, since a negative value was passed the last element was removed and all the other values were passed as an array.

Читайте также:  Add button image with css

Limitation and Caveats — PHP Explode

Note that Explode will throw a Valueerror if the separator parameter is an empty string. Other than this, there are no major constraints in the explode function.

We work with skilled PHP developers to build amazing products. Do check out our services.

Источник

explode

Возвращает массив строк, полученных разбиением строки string с использованием delimiter в качестве разделителя.

Список параметров

Если аргумент limit является положительным, возвращаемый массив будет содержать максимум limit элементов, при этом последний элемент будет содержать остаток строки string .

Если параметр limit отрицателен, то будут возвращены все компоненты кроме последних — limit .

Если limit равен нулю, то он расценивается как 1.

Замечание:

По историческим причинам, функции implode() можно передавать аргументы в любом порядке, но для explode() это недопустимо. Убедитесь в том, что delimiter указан перед аргументом string .

Возвращаемые значения

Возвращает массив ( array ) строк ( string ), созданный делением параметра string по границам, указанным параметром delimiter .

Если delimiter является пустой строкой («»), explode() возвращает FALSE . Если delimiter не содержится в string , и используется отрицательный limit , то будет возвращен пустой массив ( array ), иначе будет возвращен массив, содержащий string .

Список изменений

Версия Описание
5.1.0 Добавлена поддержка отрицательных значений limit

Примеры

Пример #1 Пример использования explode()

// Пример 1
$pizza = «кусок1 кусок2 кусок3 кусок4 кусок5 кусок6» ;
$pieces = explode ( » » , $pizza );
echo $pieces [ 0 ]; // кусок1
echo $pieces [ 1 ]; // кусок2

// Пример 2
$data = «foo:*:1023:1000::/home/foo:/bin/sh» ;
list( $user , $pass , $uid , $gid , $gecos , $home , $shell ) = explode ( «:» , $data );
echo $user ; // foo
echo $pass ; // *

Пример #2 Пример возвращаемого значения explode()

/*
Строка, которая не содержит разделителя, будет
просто возвращать массив с одним значением оригинальной строки.
*/
$input1 = «hello» ;
$input2 = «hello,there» ;
var_dump ( explode ( ‘,’ , $input1 ) );
var_dump ( explode ( ‘,’ , $input2 ) );

Результат выполнения данного примера:

array(1) ( [0] => string(5) "hello" ) array(2) ( [0] => string(5) "hello" [1] => string(5) "there" )

Пример #3 Примеры с использованием параметра limit

// положительный лимит
print_r ( explode ( ‘|’ , $str , 2 ));

// отрицательный лимит (начиная с PHP 5.1)
print_r ( explode ( ‘|’ , $str , — 1 ));
?>

Результат выполнения данного примера:

Array ( [0] => один [1] => два|три|четыре ) Array ( [0] => один [1] => два [2] => три )

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

Смотрите также

  • preg_split() — Разбивает строку по регулярному выражению
  • str_split() — Преобразует строку в массив
  • mb_split() — Разделение строк в многобайтных кодировках, используя регулярное выражение
  • str_word_count() — Возвращает информацию о словах, входящих в строку
  • strtok() — Разбивает строку на токены
  • implode() — Объединяет элементы массива в строку

Источник

explode

Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string separator .

Parameters

If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string .

If the limit parameter is negative, all components except the last — limit are returned.

Читайте также:  Android studio kotlin search

If the limit parameter is zero, then this is treated as 1.

Note:

Prior to PHP 8.0, implode() accepted its parameters in either order. explode() has never supported this: you must ensure that the separator argument comes before the string argument.

Return Values

Returns an array of string s created by splitting the string parameter on boundaries formed by the separator .

If separator is an empty string («»), explode() throws a ValueError . If separator contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned. If separator values appear at the start or end of string , said values will be added as an empty array value either in the first or last position of the returned array respectively.

Changelog

Version Description
8.0.0 explode() will now throw ValueError when separator parameter is given an empty string ( «» ). Previously, explode() returned false instead.

Examples

Example #1 explode() examples

// Example 1
$pizza = «piece1 piece2 piece3 piece4 piece5 piece6» ;
$pieces = explode ( » » , $pizza );
echo $pieces [ 0 ]; // piece1
echo $pieces [ 1 ]; // piece2

// Example 2
$data = «foo:*:1023:1000::/home/foo:/bin/sh» ;
list( $user , $pass , $uid , $gid , $gecos , $home , $shell ) = explode ( «:» , $data );
echo $user ; // foo
echo $pass ; // *

Example #2 explode() return examples

/*
A string that doesn’t contain the delimiter will simply
return a one-length array of the original string.
*/
$input1 = «hello» ;
$input2 = «hello,there» ;
$input3 = ‘,’ ;
var_dump ( explode ( ‘,’ , $input1 ) );
var_dump ( explode ( ‘,’ , $input2 ) );
var_dump ( explode ( ‘,’ , $input3 ) );

The above example will output:

array(1) ( [0] => string(5) "hello" ) array(2) ( [0] => string(5) "hello" [1] => string(5) "there" ) array(2) ( [0] => string(0) "" [1] => string(0) "" )

Example #3 limit parameter examples

// positive limit
print_r ( explode ( ‘|’ , $str , 2 ));

// negative limit
print_r ( explode ( ‘|’ , $str , — 1 ));
?>

The above example will output:

Array ( [0] => one [1] => two|three|four ) Array ( [0] => one [1] => two [2] => three )

Notes

Note: This function is binary-safe.

See Also

  • preg_split() — Split string by a regular expression
  • str_split() — Convert a string to an array
  • mb_split() — Split multibyte string using regular expression
  • str_word_count() — Return information about words used in a string
  • strtok() — Tokenize string
  • implode() — Join array elements with a string

User Contributed Notes 3 notes

Note that an empty input string will still result in one element in the output array. This is something to remember when you are processing unknown input.

For example, maybe you are splitting part of a URI by forward slashes (like «articles/42/show» => [«articles», «42», «show»]). And maybe you expect that an empty URI will result in an empty array («» => []). Instead, it will contain one element, with an empty string:

$uri = » ;
$parts = explode ( ‘/’ , $uri );
var_dump ( $parts );

Be careful, while most non-alphanumeric data types as input strings return an array with an empty string when used with a valid separator, true returns an array with the string «1»!

Читайте также:  Sppcode Live Chat Tutorial

var_dump(explode(‘,’, null)); //array(1) < [0]=>string(0) «» >
var_dump(explode(‘,’, false)); //array(1) < [0]=>string(0) «» >

var_dump(explode(‘,’, true)); //array(1) < [0]=>string(1) «1» >

If you want to directly take a specific value without having to store it in another variable, you can implement the following:

echo $status_only = explode(‘-‘, $status)[0];

Источник

PHP Explode – How to Split a String into an Array

Kolade Chris

Kolade Chris

PHP Explode – How to Split a String into an Array

The PHP explode() function converts a string to an array. Each of the characters in the string is given an index that starts from 0. Like the built-in implode() function, the explode function does not modify the data (string).

Syntax of the explode() Function

The explode() function takes in three parameters:

The full syntax looks like this:

explode(separator, string, limit) 

Unlike implode() which works even if the separator is not provided, the explode() function won’t work without the separator. So, just like the string split into an array, the separator is required. You can use the limit parameter to specify the number of arrays expected. It is optional.

Examples of implode()

Let’s say that I have the string «Hello World». If the string is passed into an explode() function, Hello takes an index of 0 in the array, and World takes an index of 1. Remember that arrays use zero-based indexing.

$str = "Hello world"; $newStr = explode(" ", $str); // We are printing an array, so we can use print_r() print_r($newStr); 

ss1-3

If you specify a limit in the explode() function, the index(es) won’t be more than that number. For example, if you specify 2, all the strings would show, but the index won’t be more than 2.

$str = "CSS, HTML, PHP, Java, JavaScript"; $newStr = explode(" ", $str, 2); // We are printing an array, so we can use print_r() print_r($newStr); 

ss2-3

You can see that the first element takes an index of 0 and the rest of the comma-separated elements take 1. The index is not more than the limit of 2 specified.

The explode() function looks at spaces in the string to split the string into an array. If you type two different words together, they are treated as one:

$str = "CSS HTMLPHP Java JavaScript"; $newStr = explode( " ", $str); // We are printing an array, so we can use print_r() print_r($newStr); 

ss5-2

You can see that HTML and PHP got ptinted together because there was no space between them.

Conclusion

This article showed you how to use the explode() function in PHP.

Note that unlike implode() which works without the separator, the separator is very important in explode() . If you don’t specify a separator, explode() won’t work as expected.

$str = "CSS, HTML, PHP, Java, JavaScript"; $newStr = explode($str, 2); // We are printing an array, so we can use print_r() print_r($newStr); 

ss3-3

And if you leave the separator as an empty string, you get an error:

Источник

Оцените статью