Массивы в php разделитель

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

Для того, чтобы преобразовать строку в массив по разделителю, можно использовать функцию 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. preg_split: разбить строку на массив по регулярному выражению

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

// разбиваем строку по произвольному числу запятых и пробельных символов, // которые включают в себя " ", \r, \t, \n и \f $keywords = preg_split("/[\s,]+/", "hypertext language, programming"); print_r($keywords);
/* Array ( [0] => hypertext [1] => language [2] => programming ) */

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

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

$str = "Hello Friend"; $arr2 = str_split($str, 3); print_r($arr2)
Array ( [0] => Hel [1] => lo [2] => Fri [3] => end )

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

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

Читайте также:  border-left-width

Источник

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.

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»!

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];

Источник

implode

Альтернативная сигнатура (не поддерживается с именованными аргументами):

Устаревшая сигнатура (устарела с PHP 7.4.0, удалена в PHP 8.0.0):

Объединяет элементы массива с помощью строки separator .

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

Необязательный. По умолчанию равен пустой строке.

Массив объединяемых строк.

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

Возвращает строку, содержащую строковое представление всех элементов массива в указанном порядке, с разделителем между каждым элементом.

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

Версия Описание
8.0.0 Передача separator после array больше не поддерживается.
7.4.0 Передача separator после array (т.е. использование недокументированного порядка параметров) устарела.

Примеры

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

$array = [ ‘имя’ , ‘почта’ , ‘телефон’ ];
var_dump ( implode ( «,» , $array )); // string(32) «имя,почта,телефон»

// Пустая строка при использовании пустого массива:
var_dump ( implode ( ‘привет’ , [])); // string(0) «»

// Параметр separator не обязателен:
var_dump ( implode ([ ‘a’ , ‘b’ , ‘c’ ])); // string(3) «abc»

Примечания

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

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

  • explode() — Разбивает строку с помощью разделителя
  • preg_split() — Разбивает строку по регулярному выражению
  • http_build_query() — Генерирует URL-кодированную строку запроса

User Contributed Notes 14 notes

it should be noted that an array with one or no elements works fine. for example:

$a1 = array( «1» , «2» , «3» );
$a2 = array( «a» );
$a3 = array();

echo «a1 is: ‘» . implode ( «‘,'» , $a1 ). «‘
» ;
echo «a2 is: ‘» . implode ( «‘,'» , $a2 ). «‘
» ;
echo «a3 is: ‘» . implode ( «‘,'» , $a3 ). «‘
» ;
?>

will produce:
===========
a1 is: ‘1’,’2′,’3′
a2 is: ‘a’
a3 is: »

It’s not obvious from the samples, if/how associative arrays are handled. The «implode» function acts on the array «values», disregarding any keys:

$a = array( ‘one’ , ‘two’ , ‘three’ );
$b = array( ‘1st’ => ‘four’ , ‘five’ , ‘3rd’ => ‘six’ );

echo implode ( ‘,’ , $a ), ‘/’ , implode ( ‘,’ , $b );
?>

outputs:
one,two,three/four,five,six

Can also be used for building tags or complex lists, like the following:

?>

This is just an example, you can create a lot more just finding the right glue! 😉

It might be worthwhile noting that the array supplied to implode() can contain objects, provided the objects implement the __toString() method.

class Foo
protected $title ;

public function __construct ( $title )
$this -> title = $title ;
>

public function __toString ()
return $this -> title ;
>
>

$array = [
new Foo ( ‘foo’ ),
new Foo ( ‘bar’ ),
new Foo ( ‘qux’ )
];

echo implode ( ‘; ‘ , $array );
?>

will output:

If you want to implode an array of booleans, you will get a strange result:
var_dump ( implode ( » ,array( true , true , false , false , true )));
?>

Output:
string(3) «111»

TRUE became «1», FALSE became nothing.

If you want to implode an array as key-value pairs, this method comes in handy.
The third parameter is the symbol to be used between key and value.

function mapped_implode ( $glue , $array , $symbol = ‘=’ ) return implode ( $glue , array_map (
function( $k , $v ) use( $symbol ) <
return $k . $symbol . $v ;
>,
array_keys ( $array ),
array_values ( $array )
)
);
>

echo mapped_implode ( ‘, ‘ , $arr , ‘ is ‘ );

// output: x is 5, y is 7, z is 99, hello is World, 7 is Foo

Sometimes it’s necessary to add a string not just between the items, but before or after too, and proper handling of zero items is also needed.
In this case, simply prepending/appending the separator next to implode() is not enough, so I made this little helper function.

function wrap_implode ( $array , $before = » , $after = » , $separator = » ) if( ! $array ) return » ;
return $before . implode ( » < $after >< $separator > < $before >» , $array ) . $after ;
>

echo wrap_implode ([ ‘path’ , ‘to’ , ‘file.php’ ], ‘/’ );
// «/path/to/file.php»

$pattern = ‘#’ . wrap_implode ([ 4 , 2 , 2 ], ‘\d’ , ‘[-.]’ ) . ‘#’ ;
echo $pattern , «\n» ; // #\d[-.]\d[-.]\d#
echo preg_replace ( $pattern , ‘[REDACTED]’ , ‘The UFO appeared between 2012-12-24 and 2013.01.06 every night.’ );
// ‘The UFO appeared between [REDACTED] and [REDACTED] every night.

echo wrap_implode ([ ‘line’ , ‘by’ , ‘line’ ], ‘‘ , ‘‘ , ‘
‘ );
// line
by
line

It may be worth noting that if you accidentally call implode on a string rather than an array, you do NOT get your string back, you get NULL:
var_dump ( implode ( ‘:’ , ‘xxxxx’ ));
?>
returns
NULL

This threw me for a little while.

Even handier if you use the following:

$id_nums = array( 1 , 6 , 12 , 18 , 24 );

$id_nums = implode ( «, » , $id_nums );

$sqlquery = «Select name,email,phone from usertable where user_id IN ( $id_nums )» ;

// $sqlquery becomes «Select name,email,phone from usertable where user_id IN (1,6,12,18,24)»
?>

Be sure to escape/sanitize/use prepared statements if you get the ids from users.

null values are imploded too. You can use array_filter() to sort out null values.

$ar = array( «hello» , null , «world» );
print( implode ( ‘,’ , $ar )); // hello,,world
print( implode ( ‘,’ , array_filter ( $ar , function( $v )< return $v !== null ; >))); // hello,world
?>

If you want to use a key inside array:

Example:
$arr=array(
array(«id» => 1,»name» => «Test1»),
array(«id» => 2,»name» => «Test2»),
);

echo implode_key(«,»,$arr, «name»);
OUTPUT: Test1, Test2

function implode_key($glue, $arr, $key) $arr2=array();
foreach($arr as $f) if(!isset($f[$key])) continue;
$arr2[]=$f[$key];
>
return implode($glue, $arr2);
>

It is possible for an array to have numeric values, as well as string values. Implode will convert all numeric array elements to strings.

$test = implode ([ «one» , 2 , 3 , «four» , 5.67 ]);
echo $test ;
//outputs: «one23four5.67»
?>

There is no mention of behavior on a empty array, so I tried it and here’s the result:

$ar = array();
$result = implode ( ‘,’ , $ar ); // Comma arbitrarily applied as the separator
$is_result_empty = empty( $result );
?>

$result:
$is_result_empty: 1

In other words, an empty string is the result.

* Join pieces with a string recursively .
*
* @ param mixed $glue String between pairs ( glue ) or an array pair ‘s glue and key/value glue or $pieces.
* @param iterable $pieces Pieces to implode (optional).
* @return string Joined string
*/
function double_implode($glue, iterable $pieces = null): string
$glue2 = null;
if ($pieces === null) $pieces = $glue;
$glue = »;
> elseif (is_array($glue)) list($glue, $glue2) = $glue;
>

$result = [];
foreach ($pieces as $key => $value) $result[] = $glue2 === null ? $value : $key . $glue2 . $value;
>
return implode($glue, $result);
>
?>
Examples:
$array = [‘ a ‘ => 1, ‘b’ => 2];
$str = implode($array);
$str = implode(‘ , ‘, $array);
$str = implode([‘» ‘, ‘ keyword»>, ‘, $iterator);
$str = implode([‘» ‘, ‘ foot»>+add a note

Источник

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